Skip to main content

9.8) Lists Comprehension: a For Loop in a Line


If you want to use a loop to produce a new list, use a list comprehension.

List comprehensions are essentially a concise way of producing a list; e.g. you can write out a simple for loop in one line. It’s usually used to produce a new list by performing operations on each element of a sequence.

For example, if you want to multiply each element of a list by two, you can’t simply multiply the list by two as that will repeat the list twice. You could use a for loop, but using a list comprehension is more concise and it runs quicker:

>>> numbers = [1,5,9]
>>> doubles=[i*2 for i in numbers]   # produces a list called ‘doubles’
>>> doubles
[2, 10, 18]

This is instead of:

>>> numbers = [1,5,9]
>>> doubles = []      # you need to create an empty list
>>> for i in numbers:
        doubles.append(i*2)
>>> doubles
[2, 10, 18]

If you want to understand what happens when you run this code, check out this Python Tutor example. (Notice the variable i pointing through each value in the list numbers. The result of the list comprehension is stored as a temporary variable before being assigned to the name doubles).