Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

5.12 List Comprehensions

Here, we continue discussing functional-style features with list comprehensions—a concise and convenient notation for creating new lists. List comprehensions can replace many for statements that iterate over existing sequences and create new lists, such as:

In [1]: list1 = []

In [2]: for item in range(1, 6):
   ...:     list1.append(item)
   ...:    

In [3]: list1
Out[3]: [1, 2, 3, 4, 5]

Using a List Comprehension to Create a List of Integers

We can accomplish the same task in a single line of code with a list comprehension:

In [4]: list2 = [item for item in range(1, 6)]

In [5]: list2
Out[5]: [1, 2, 3, 4, 5]

Like snippet [2]’s for statement, the list comprehension’s for clause

          for item in range(1, 6)

iterates over the sequence produced by range(1, 6). For each item, the list comprehension evaluates the expression to the left of the for clause and places the expression’s value (in this case, the item itself) in the new list. Snippet [4]’s particular comprehension could have been expressed more concisely using the function list:

          list2 = list(range(1, 6))

Mapping: Performing Operations in a List Comprehension’s Expression

A list comprehension’s expression can perform tasks, such as calculations, that map elements to new values (possibly of different types). Mapping is a common functional-style programming operation that produces a result with the same number of elements as the original data being mapped. The following comprehension maps each value to its cube with the expression item ** 3:

In [6]: list3 = [item ** 3 for item in range(1, 6)]

In [7]: list3
Out[7]: [1, 8, 27, 64, 125]

Filtering: List Comprehensions with if Clauses

Another common functional-style programming operation is filtering elements to select only those that match a condition. This typically produces a list with fewer elements than the data being filtered. To do this in a list comprehension, use the if clause. The following includes in list4 only the even values produced by the for clause:

In [8]: list4 = [item for item in range(1, 11) if item % 2 == 0]

In [9]: list4
Out[9]: [2, 4, 6, 8, 10]

List Comprehension That Processes Another List’s Elements

The for clause can process any iterable. Let’s create a list of lowercase strings and use a list comprehension to create a new list containing their uppercase versions:

In [10]: colors = ['red', 'orange', 'yellow', 'green', 'blue']

In [11]: colors2 = [item.upper() for   item in colors]

In [12]: colors2
Out[12]: ['RED', 'ORANGE', 'YELLOW', 'GREEN', 'BLUE']

In [13]: colors
Out[13]: ['red', 'orange', 'yellow', 'green', 'blue']
  • + Share This
  • 🔖 Save To Your Account