Original Translation
45
# Given the list L, make a list of all strings # containing the substring S. sublist = filter( lambda s, substring=S: string.find(s, substring) != -1, L)
46
Because of Python's scoping rules, a default argument is used so that the anonymous function created by the :keyword:`lambda` statement knows what substring is being searched for. List comprehensions make this cleaner::
47
sublist = [ s for s in L if string.find(s, S) != -1 ]
48
List comprehensions have the form::
49
[ expression for expr in sequence1 for expr2 in sequence2 ... for exprN in sequenceN if condition ]
50
The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are *not* iterated over in parallel, but from left to right; this is explained more clearly in the following paragraphs. The elements of the generated list will be the successive values of *expression*. The final :keyword:`if` clause is optional; if present, *expression* is only evaluated and added to the result if *condition* is true.
51
To make the semantics very clear, a list comprehension is equivalent to the following Python code::
52
for expr1 in sequence1: for expr2 in sequence2: ... for exprN in sequenceN: if (condition): # Append the value of # the expression to the # resulting list.
53
This means that when there are multiple :keyword:`for`...\ :keyword:`in` clauses, the resulting list will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long::
54
seq1 = 'abc' seq2 = (1,2,3) >>> [ (x,y) for x in seq1 for y in seq2] [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]