Python Statements and Functions (
Page 1 of 4 )
In this seventh part of a nine-part series on the Python language, we continue our discussion of statements and move on to functions. This article is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
List comprehensions
A common use of a for loop is to inspect each item in an iterable and build a new list by appending the results of an expression computed on some or all of the items. The expression form known as a list comprehension lets you code this common idiom concisely and directly. Since a list comprehension is an expression (rather than a block of statements), you can use it wherever you need an expression (e.g., as an argument in a function call, in a return statement, or as a subexpression for some other expression).
A list comprehension has the following syntax:
[ expression for target in iterable lc-clauses ]
target and iterable are the same as in a regular for statement. You must enclose the expression in parentheses if it indicates a tuple.
lc-clauses is a series of zero or more clauses, each with one of the following forms:
for target in iterable
if expression
target and iterable in each for clause of a list comprehension have the same syntax and meaning as those in a regular for statement, and the expression in each if clause of a list comprehension has the same syntax and meaning as the expression in a regular if statement.
A list comprehension is equivalent to a for loop that builds the same list by repeated calls to the resulting list's append method. For example (assigning the list comprehension result to a variable for clarity):
result1 = [x+1 for x in some_sequence]
is the same as the for loop:
result2 = []
for x in some_sequence:
result2.append(x+1)
Here's a list comprehension that uses an if clause:
result3 = [x+1 for x in some_sequence if x>23]
This list comprehension is the same as a for loop that contains an if statement:
result4 = []
for x in some_sequence:
if x>23:
result4.append(x+1)
And here's a list comprehension that uses a for clause:
result5 = [x+y for x in alist for y in another]
This is the same as a for loop with another for loop nested inside:
result6 = []
for x in alist:
for y in another:
result6.append(x+y)
As these examples show, the order of for and if in a list comprehension is the same as in the equivalent loop, but in the list comprehension, the nesting remains implicit.