List Comprehensions

Remember how we used lambda functions along with map() and filter() to apply an operation to list members or to filter out list members based on criteria via a conditional expression? Well, list comprehensions simplify that task and improve performance by bypassing the necessity of using lambda along with functional programming built-in functions. List comprehensions allow you to provide an operation directly with an iteration over the original list sequence.

Let's take a look at the simpler list comprehension syntax first:

[ expression
					for
					iterative_var
					in
					sequence ]

The core of this statement is the for loop, which iterates over each item of sequence. The prefixed expression is applied for each member of the sequence, and the resulting values comprise the list that the expression yields. The iteration variable need not be part of the expression.

Recall the following code seen earlier in the text (Chapter 11, Functions) which utilizes a lambda function to square the members of a sequence:

>>> map(( lambda x: x ** 2), range(6))
[0, 1, 4, 9, 16, 25]

We can replace this code with the following list comprehension statement:

>>> [ x ** 2 for x in range(6) ]
[0, 1, 4, 9, 16, 25]

In the new statement, only one function call (range()) is made (as opposed to three—range(), map(), and the lambda function). You may also use parentheses around the expression if “[ (x ** 2) for x in range(6) ]” is easier for you to read. This syntax for list comprehensions can be a substitute for and is more efficient than using the map() built-in function along with lambda.

List comprehensions also support an extended syntax with the if statement:

[ expression
					for
					iterative_var
					in
					sequence
					if
					cond_expression]

This syntax will filter or “capture” sequence members only if they meet the condition provided for in the cond_expression conditional expression during iteration.

Recall the following odd() function below, which determines whether a numeric argument is odd or even (returning 1 for odd numbers and 0 for even numbers):

					def odd(n):
    return n % 2

We were able to take the core operation from this function, and use it with filter() and lambda to obtain the set of odd numbers from a sequence:

>>> seq = [11, 10, 9, 9, 10, 10, 9, 8, 23, 9, 7, 18, 12, 11, 12]
>>> filter(lambda x: x % 2, seq)
[11, 9, 9, 9, 23, 9, 7, 11]

As in the previous example, we can bypass the use of filter() and lambda to obtain the desired set of numbers with list comprehensions:

>>> [ x for x in seq if x % 2 ]
[11, 9, 9, 9, 23, 9, 7, 11]

List comprehensions also support multiple nested for loops and more than one if clause. Please see the documentation including the “What's New” online document for more information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset