In [1]:
x = range(10)
In [2]:
x
Out[2]:
List comprehensions are something that are very important in python. You’ll come across them a lot and they are described as “pythonic” or typical to python.
They’re a python specific way of doing filters and maps.
Applying filters isn’t as popular nor ubiquitous in python as doing list comprehensions. You will certainly come across these a lot in your area of study and they’re worth understanding.
In [3]:
[item**3 for item in x]
Out[3]:
In [4]:
[item for item in x if item % 2 == 0]
Out[4]:
In [5]:
[item**2 for item in x if item % 2 == 0]
Out[5]:
In [6]:
test_list = [
"hello",
"x,y,z. i like this.",
"this is two xx",
"this, x, here x is, here it is againx"
]
Filter out the items that have x less than 2 times (we keep those that have "x" more than 2 times)
convert our list "x" into a list of floats
In [7]:
[item for item in test_list if item.count("x") >= 2]
Out[7]:
In [8]:
x
Out[8]:
In [9]:
[float(item) for item in x]
Out[9]:
In [10]:
def cube(num):
return num**3
In [11]:
cubed = [cube(item) for item in x]
In [12]:
cubed
Out[12]:
In [ ]: