23.4. List ComprehensionsΒΆ

Python provides an alternative way to do map and filter operations, called a list comprehension. Many programmers find them easier to understand and write. List comprehensions are concise ways to create lists from other lists. The general syntax is:

[<expression> for <item> in <sequence> if <condition>]

where the if clause is optional. For example,

The expression is value * 2. The item variable is value and the sequence is things. This is an alternative way to perform a mapping operation. As with map, each item in the sequence is transformed into an item in the new list. Instead of the iteration happening automatically, however, we have adopted the syntax of the for loop which may make it easier to understand.

Just as in a regular for loop, the part of the statement for value in things says to execute some code once for each item in things. Each time that code is executed, value is bound to one item from things. The code that is executed each time is the expression at the beginning, value * 2, rather than a block of code indented underneath the for statement. The other difference from a regular for loop is that each time the expression is evaluated, the resulting value is appended to a list. That happens automatically, without the programmer explicitly initializing an empty list or appending each item.

The if clause of a list comprehension can be used to do a filter operation. To perform a pure filter operation, the expression can be simply the variable that is bound to each item. For example, the following list comprehension will keep only the even numbers from the original list.

You can also combine map and filter operations by chaining them together, or with a single list comprehension.

Check your understanding

    AdAccum-4-1: What is printed by the following statements?

    alist = [4,2,8,6,5]
    blist = [num*2 for num in alist if num%2==1]
    print(blist)
    
  • [4,2,8,6,5]
  • Items from alist are doubled before being placed in blist.
  • [8,4,16,12,10]
  • Not all the items in alist are to be included in blist. Look at the if clause.
  • 10
  • The result needs to be a list.
  • [10]
  • Yes, 5 is the only odd number in alist. It is doubled before being placed in blist.
2. The for loop below produces a list of numbers greater than 10. Below the given code, use list comprehension to accomplish the same thing. Assign it the the variable lst2. Only one line of code is needed.
3. Write code to assign to the variable compri all the values of the key name in the dictionary tester. Do this using list comprehension.
Next Section - 23.5. Zip