list example

P

PAolo

Hi,
I wrote this small example to illustrate the usage of lists:

even=[]
odd=[]

for i in range(1,10):
if i%2:
odd.append(i)
else:
even.append(i)

print "odd: "+str(odd)
print "even: "+str(even)

numbers=even
numbers.extend(odd)
print "numbers:"+str(numbers)
numbers.sort()
print "sorted numbers:"+str(numbers)


any comment, suggestion? Is there something not elegant?

Thnx
PAolo
 
B

bearophileHUGS

PAolo>any comment, suggestion? Is there something not elegant?<

Here you can see many little differences, some of them reflect just my
style, but some other of them are Python standard style guidelines:

even = []
odd = []

for i in xrange(1, 10):
if i % 2:
odd.append(i)
else:
even.append(i)

print "Odd:", odd
print "Even:", even

numbers = even + odd
print "Numbers:", numbers
numbers.sort()
print "Sorted numbers:", numbers


There are surely more compact versions of that, but compactness is
usually less important than clarity, expecially for someone that is
learning Python.
This is a more compact version (with the suggestion by Wojciech Mula,
modified in two ways):

even = range(1, 10)[1::2]
odd = range(1, 10)[0::2]

print "Odd:", odd
print "Even:", even

numbers = even + odd
print "Numbers:", numbers
print "Sorted numbers:", sorted(numbers)


Bye,
bearophile
 
P

Paolo Pantaleo

2006/4/22 said:
No substantive problems. The str() calls are unnecessary, print calls
list.__str__ already. You can replace the loop with list comprehensions or
slices. Same result, a bit more succinct. See these pages for more:

http://docs.python.org/lib/typesseq.html
http://docs.python.org/tut/node7.html (section 5.1.4)

Thnx, I didn't catch the use of colon in print...

Thanks to the other posting, but actually I want to write some code
that one can modify to his own needings

PAolo
 
A

Andrew Koenig

for i in range(1,10):
if i%2:
odd.append(i)
else:
even.append(i)

In 2.5 you'll be able to say

for i in range(1,10):
(odd if i%2 else even).append(i)

Whether you want to do this is another question entirely, of course.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Forum statistics

Threads
474,294
Messages
2,571,511
Members
48,196
Latest member
NevilleFer

Latest Threads

Top