list displays

O

Olive

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]

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

Olive
 
S

Steven D'Aprano

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.
 

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

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top