Original Translation
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)]
55
To avoid introducing an ambiguity into Python's grammar, if *expression* is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct::
56
# Syntax error [ x,y for x in seq1 for y in seq2] # Correct [ (x,y) for x in seq1 for y in seq2]