List comprehensions

Python offers a shorter syntax when you want to create a new list based on the values of an existing sequence.

For example:

names = ["Anakin", "Luke", "Leia"]
names_with_last_name = [ n+" Skywalker" for n in names]
print(names_with_last_name)
['Anakin Skywalker', 'Luke Skywalker', 'Leia Skywalker']

Other examples:

Using ranges:

length = 15
exponents2 = [ 2**i for i in range(length)]
print(exponents2)
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384]

Nesting comprehensions:

w = 4
h = 4
zero_matrix = [ [0 for j in range(h)] for i in range(w)]
print(zero_matrix)
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Examples:

Checking conditions:

x = [3, 6, -2, 5, -12, 5, -1]
only_positives = [i for i in x if i > 0]
print(only_positives)
[3, 6, 5, 5]
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
['apple', 'banana', 'mango']

Creating a scenario (see our tile drawing exercise)

level = [['s' if j<8 else 'g' for i in range(10)] for j in range(10)]