List Comprehension

Reference Documents

List Comprehension

  • Provides a concise way to create lists.
  • Consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists
  • The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
  • Aways returns a result list.

If you used to do it like this:


In [ ]:
# note this is psuedo-code; will not actually run
new_list = []
for i in old_list:
    if filter(i):
       new_list.append(expressions(i))

You can obtain the same thing using list comprehension:


In [ ]:
new_list = [expression(i) for i in old_list if filter(i)]

A working example:


In [ ]:
old_list = ['bob','loblaw','law blog']
new_list = []
for i in old_list:
    if 'law' in i:
       new_list.append(i.strip('law'))

print new_list

Syntax

The list comprehension starts with a '[' and ']', to help you remember that the result is going to be a list.

The basic syntax is


In [ ]:
[ expression for item in list if conditional ]

This is equivalent to:


In [ ]:
for item in list:
    if conditional:
        expression

Here is what it does:


In [ ]:
new_list = [expression(i) for i in old_list if filter(i)]

Examples


In [ ]:
x = [i for i in range(10)]
print x

In [ ]:
# You can either use loops:
squares = []

for x in range(10):
    squares.append(x**2)
 
print squares

# Or you can use list comprehensions to get the same result:
squares = [x**2 for x in range(10)]

print squares

In [ ]:
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
print numbers

In [ ]:
# Create a function and name it double:
def double(x):
  return x*2

# If you now just print that function with a value in it, it should look like this:
print double(10)

In [ ]:
# You can apply function to a list
A = [double(x) for x in range(10)]
print A

In [ ]:
# You can put in conditions:
B = [double(x) for x in range(10) if x%2==0]
print B

In [ ]:
# You can add more arguments:
C = [x+y for x in [10,30,50] for y in [20,40,60]]
print C

In [ ]:
#List comprehensions can contain complex expressions and nested functions:
from math import pi
D = [str(round(pi, i)) for i in range(1, 6)]
print D

In [ ]:
# Calculation of the prime numbers between 1 and 100 using the sieve of Eratosthenes:
n = 100

# Without List Comprehension
#---------------------------
noprimes = [] 
for i in range(2, 8): 
    for j in range(i*2, n, i): 
        noprimes.append(j) 
primes = [] 
for x in range(2, n): 
    if x not in noprimes: 
        primes.append(x)

# With List Comprehension
#------------------------
noprimes = [j for i in range(2, 8) for j in range(i*2, n, i)]
primes = [x for x in range(2, n) if x not in noprimes]
print primes

Problem 1


In [ ]:
# We want to simulate a series of coin tosses where 0 is heads and 1 is tails.
from random import random
n = 10
results = [] 
for x in range(n): 
    results.append(int(round(random())))

Use a list comprehension to make it more concise.


In [ ]:

Problem 2

Use list comprehension to remove all the vowels from the sentence


In [ ]:
sentence = "The GFSC Python Bootcamp is a great opportunity to learn Python programming."
vowels = 'aeiou'

In [ ]: