One of Python's functional programming constructs, and quite possibly the easiest to grasp. It essentially applies some expression to each element of an iterator (usually a list or a tuple) and places the result, if it meets some condition, in a new list which it returns. It can be thought of as a map() with an implied filter(), but I just like to think of it as a list comprehension.

syntax :
[expression for item1 in sequence1
            for item2 in sequence2
            for item3 in sequence3
            ...
            for itemN in sequenceN
            if condition]


Example

Lets say one has the string "(foo)(bar)(baz)" and one wishes to obtain the list ["foo", "bar", "baz"] from it. Simply using the split() method of the string doesn't quite take care of everything since "(foo)(bar)(baz)".split( ")" ) returns the list ['(foo', '(bar', '(baz', ''] which both has an empty element and starts each string with a leading parenthesis. So, the obvious way to handle this is:
>>> s = "(foo)(bar)(baz)"
>>> t = s.split( ")" )
>>> t
['(foo', '(bar', '(baz', '']
>>> l = []
>>> for x in t :
...     if x :
...          l.append(x[1:])   #where x1: is the slice operator
...
>>> l
['foo', 'bar', 'baz']
Which works reasonably well, however, if one understands list comprehensions, one can simply say :
>>> s = "(foo)(bar)(baz)"
>>> l = [ x[1:] for x in s.split( ")" ) if x ]
>>> l
['foo', 'bar', 'baz']




And for those who prefer their code to be write-only, the same thing could effectively be done using a regexp:
>>> s = "(foo)(bar)(baz)"
>>> import re
>>> l = re.findall(r'\((.*?)\)', s)
>>> l
['foo', 'bar', 'baz']
Thanks to erwin from #python for this

Log in or register to write something here or to contact authors.