Raw Python - List Comprehensions


In [1]:
x = range(10)

In [2]:
x


Out[2]:
range(0, 10)

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]:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

In [4]:
[item for item in x if item % 2 == 0]


Out[4]:
[0, 2, 4, 6, 8]

In [5]:
[item**2 for item in x if item % 2 == 0]


Out[5]:
[0, 4, 16, 36, 64]

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]:
['this is two xx', 'this, x, here x is, here it is againx']

In [8]:
x


Out[8]:
range(0, 10)

In [9]:
[float(item) for item in x]


Out[9]:
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

In [10]:
def cube(num):
    return num**3

In [11]:
cubed = [cube(item) for item in x]

In [12]:
cubed


Out[12]:
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

In [ ]: