Python

List comprehensions

What is list comprehension?

List comprehensions are an easy way to create lists.

Its much easier to write a one liner than it is to write a for loop, just for creating a list. This _ one liner_ is called a list comprehension.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Example

Assume we want to create a list containing 100 numbers. Manually that would be a lot of typing work. So we would use a for loop, right?

We can define a for loop to fill the list.

numbers = []

for i in range(0,100):
numbers.append(i)

print(numbers)

We can replace it with a one liners, which is how we obtain the same result:

numbers = [ x for x in range(100) ]

This is also useful if you want to create large lists.

Note: List comprehensions can include function calls and expressions.

Assume we want the square roots to 100:

import math

numbers = [ math.sqrt(x) for x in range(100) ]
print(numbers)

Previous Post Next Post

Cookie policy | Privacy policy | ©