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:
In [1]:
# Grab every letter in string
lst = [x for x in 'word']
In [2]:
# Check
lst
Out[2]:
In [1]:
# Square numbers in range and turn into list
lst = [x**2 for x in range(0,11)]
In [2]:
lst
Out[2]:
In [5]:
# Check for even numbers in a range
lst = [x for x in range(11) if x % 2 == 0]
In [6]:
lst
Out[6]:
In [7]:
# Convert Celsius to Fahrenheit
celsius = [0,10,20.1,34.5]
fahrenheit = [ ((float(9)/5)*temp + 32) for temp in Celsius ]
fahrenheit
Out[7]:
In [8]:
lst = [ x**2 for x in [x**2 for x in range(11)]]
lst
Out[8]:
Later on in the course we will learn about generator comprehensions. After this lecture you should feel comfortable reading and writing basic list comprehensions.