[Tutor] What is this [] construction?

Alan Gauld alan.gauld at btinternet.com
Wed Mar 4 08:56:02 CET 2009


"Andre Engels" <andreengels at gmail.com> wrote

>> What is this: d = [ int(x) for x in s.split(":") ]

> That's called list comprehension. The notation
> [f(x) for x in A if p(x)]
> means:
> Form a list in the following way:

For Wayne's benefit...
You will also find a similar construction in parens called 
a generator expression (like tuoles the parens aren't always 
necessary but usually help). That produces an iterable that 
you can loop over without actually creating a list per se.

ie you can write:

>>> foo = [1,2,3,4]
>>> for n in (x for x in foo if x % 2):
...           print n
...    
1
3

In Python v3 list comprehensions and generator expressions 
have been "merged" in that putting a GE inside [] has the 
same effect as a LC. In practice this makes little or no difference 
to the programmer its just how Python handles it behind the 
scenes.

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/l2p/





More information about the Tutor mailing list