06-List Comprehensions
06-List Comprehensions
List Comprehensions
In addition to sequence operations and list methods, Python includes a more advanced operation
called a list comprehension.
List comprehensions allow us to build out lists using a different notation. You can think of it as
essentially a one line for loop built inside of brackets. For a simple example:
Example 1
In [1]: # Grab every letter in string
lst = [x for x in 'word']
In [2]: # Check
lst
This is the basic idea of a list comprehension. If you're familiar with mathematical notation this
format should feel familiar for example: x^2 : x in { 0,1,2...10 }
Example 2
In [3]: # Square numbers in range and turn into list
lst = [x**2 for x in range(0,11)]
In [4]: lst
Example 3
Let's see how to add in if statements:
In [6]: lst
Example 4
fahrenheit
Example 5
We can also perform nested list comprehensions, for example:
Out[8]: [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]
Later on in the course we will learn about generator comprehensions. After this lecture you should
feel comfortable reading and writing basic list comprehensions.