[expression for var-1 in seq-1 if condition-1 for var-2 in seq-2 if condition-2 ...]and the returned value is a list containing expression evaluated at each combination of var-1, var-2,
>>> oldlist = [7,9,3,4,1,12] >>> newlist = [] >>> for i in oldlist: ... newlist.append(i*i) ... >>> newlist [49, 81, 9, 16, 1, 144]Using a list comprehension, we can express this more succinctly:
>>> newlist = [i * i for i in oldlist]By using if clauses within the list comprehension, we can be more selective about the elements we return:
>>> [i * i for i in oldlist if i % 2 == 1] [49, 81, 9, 1]When you have more than one for clause, all possible combinations of the variables in the for clauses will be evaluated:
>>> [(x,y) for x in range(3) for y in range(4)] [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]if clauses can be added after either of the for clauses; to refer to combinations involving all the variables, use an if clause at the very end:
>>> [(x,y) for x in range(3) if x in (1,2) for y in range(4) if y == 0] [(1, 0), (2, 0)] >>> [(x,y) for x in range(3) for y in range(4) if x + y < 3] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0)]