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
.



Relevant Pages

  • Re: Loop in list.
    ... Jim wrote: ... >I don't see reference for it in any of the books. ... It's a list comprehension. ... and I realize I'm probably in the minority on ...
    (comp.lang.python)
  • Re: Dangerous behavior of list(generator)
    ... of a list comprehension. ... list comps to also trap StopIteration raised in the expression part, ... def gen(items, expr, cond): ...
    (comp.lang.python)
  • Re: Deprecated: list comp leak use
    ... >> The name i was bound within the list comprehension. ... The Reference ... Terry J. Reedy ...
    (comp.lang.python)
  • Re: Do this as a list comprehension?
    ... |> I can't think of how the structure of the list comprehension would work ... |> if list comps were capable of doing everything a zip could do. ... Of course, enumerateis just a facade over zip, ...
    (comp.lang.python)
  • Re: Do this as a list comprehension?
    ... I can't think of how the structure of the list comprehension would work ... sequences to produce each item in the tuple. ... if list comps were capable of doing everything a zip could do. ...
    (comp.lang.python)