Python For GCSE
List Comprehensions

List comprehensions are not part of the specifcations for GCSE Computer Science. They are an example of what is called syntactic sugar. Syntactic sugar is an optional syntax in a programming language that makes things 'sweeter' or easier to write. List comprehensions are a nice way to define a list in a single line of code.

In the following example, the list es is a sublist of names which contain the letter 'e'. This is how we might write this in Python without using a list comprehension.

names = ["Andrew", "Barbara", "Charlie", "Dora"]

es = []
for n in names:
    if "e" in n:
        es.append(n)
print(es)

Using a list comprehension, we can get the same effect with,

names = ["Andrew", "Barbara", "Charlie", "Dora"]

e = [n for n in names if "e" in n]
print(e)

The if part of the comprehension is optional. For example,

squares = [n*n for n in range(1,11)]
print(squares)

More often than not, I find myself using list comprehensions to make transformations when copying items from a list.

names = ["Andrew", "Barbara", "Charlie", "Dora"]

ups = [n.upper() for n in names]
print(ups)