Python

How to use list comprehensions

Basic List Comprehension
[ Formula for variable in iterable ]

For example,
[i*i for i in range(101)]
If you were to write this without using list comprehensions, it would be:
square = []
for i in range(101):
    square.append(i*i)

Alternatively, you can use the map function:
def sq(x):
    return x*x
list(map(sq, range(101)))


[Important]
The processing speed of the script is as follows: List comprehensions > for loop > map function.
List comprehensions are simple, highly readable, and fast.

square = []
for i in range(101):
    square.append(i*i)
square[90:]

%%timeit
square = []
for i in range(101):
    square.append(i*i)


square2 = [i*i for i in range(101)]
square2[90:]

%%timeit
square2 = [i*i for i in range(101)]


def sq(x):
    return x*x
square3 = list(map(sq, range(101)))
square3[90:]

%%timeit
def sq(x):
    return x*x
square3 = list(map(sq, range(101)))