Re: list displays



On Sat, 08 Jan 2011 22:57:45 +0100, Olive wrote:

I am a newbie to python. Python supports what I thinks it is called list
display, for example:

[i for i in range(10)]
[i for i in range(10) if i<6]

This is called a list comprehension, not list display.


Does anyone know a good documentation for this. I have read the language
reference but it is confusing.

A list comprehension is syntactic sugar for a for loop. If you start with
code looking like this:

storage = []
for i in range(10):
if i < 6:
storage.append(i)


you can re-write this as a list comprehension:

storage = [i for i in range(10) if i < 6]

The source doesn't have to be range, it can be any sequence or iterator:

lengths = [len(obj) for obj in my_list_of_objects]
# like map(len, my_list_of_objects)


If you are mathematically inclined, you might also like this analogy: the
syntax for a list comprehension is similar to that of sets in mathematics.

[f(x) for x in D]

is similar to:

{ f(x) ∀ x ∈ D }
("the set of f(x) for all x element of D")


Don't waste your time with list comprehensions that just walk over the
source, doing nothing. For example:

[i for i in range(10)]

Just use list(range(10)) instead.


Where list comps get complicated is when you combine them. Nested list
comps are not too bad, although they can get messy:


[len(s) for s in [str(x) for x in [2**n for n in range(10)]]]


That's the same as:

powers_of_two = [2**n for n in range(10)]
strings = [str(x) for x in powers_of_two]
lengths = [len(s) for s in strings]


But what do you make of this?


[a*b for a in range(3) for b in range(4)]

This is like a nested for-loop:

results = []
for a in range(3):
for b in range(4):
results.append(a*b)


Hope this helps.


--
Steven
.