This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

# Comprehensions¶

In Python, there are other ways to do iterations, list (dictionary, set) comprehensions are an important and popular way that you will use frequently in your work. Comprehensions allow sequences to be created from other sequence with very compact syntax. Let’s first start to look at the list comprehension.

## List comprehension¶

CONSTRUCTION: List comprehension

[Output Input_sequence Conditions]


EXAMPLE! If x = range(5), square each number in x, and store it in a list y.

If we don’t use list comprehension, it will be something like this:

x = range(5)
y = []

for i in x:
y.append(i**2)
print(y)

[0, 1, 4, 9, 16]


But with list comprehension, we can write with just one line.

y = [i**2 for i in x]
print(y)

[0, 1, 4, 9, 16]


Besides, we can have conditions in the list comprehension as well. For example, if we just want to store the even numbers in the above example, we can do this by adding a condition in the list comprehension.

y = [i**2 for i in x if i%2 == 0]
print(y)

[0, 4, 16]


If we have two nested for loops, we can also use the list comprehensions as well. For example, we have the following two level for loops that we can do it in the list comprehension.

y = []
for i in range(5):
for j in range(2):
y.append(i + j)
print(y)

[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]

y = [i + j for i in range(5) for j in range(2)]
print(y)

[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]


## Dictionary comprehension¶

Similarly, we can do the dictionary comprehension as well. See the following example.

x = {'a': 1, 'b': 2, 'c': 3}

{key:v**3 for (key, v) in x.items()}

{'a': 1, 'b': 8, 'c': 27}


We can do set comprehension in Python, this will leave for you to explore.