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 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 = [] 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 = [] 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 = [] 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.
blog comments powered by Disqus |
|
|
|
|
|
|
|