Skip to main content

Section 15.10 List Comprehensions

Generating or modifying a list of values based on some consistent rule is a very common operation done in Python. Take, for example, generating a list of values according to a math function, or performing the same string operation on a list of words. This is common enough that Python has built-in syntax to construct these smaller, collection-producing loops succinctly. These are known as comprehensions, and can be done with several different collection types.
A comprehension that generates a list is, naturally, known as a list comprehension. List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if <condition>]
where the if clause is optional. For example,
The expression describes each element of the list that is being built. The for clause iterates through each item in a sequence. The items are filtered by the if clause if there is one. In the example above, the for statement lets item take on all the values in the list mylist. Each item is then squared before it is added to the list that is being built. The result is a list of squares of the values in mylist.
To write a primes_upto function we can use the previously-made is_prime function to filter the sequence of integers coming from a range function. In other words, for every integer from 2 up to but not including n, if the integer is prime, keep it in the list.
def primes_upto(n):
    """ Return a list of all prime numbers less than n using a list comprehension. """

    result = [num for num in range(2,n) if is_prime(num)]
    return result

Note 15.10.1.

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
Check your understanding

Checkpoint 15.10.2.

    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.
You have attempted of activities on this page.