list example

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sat Apr 22 16:58:37 EDT 2006


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




More information about the Python-list mailing list