# List comprehensions¶

In Python, a list comprehension is a convenient way to create a list.

• Have an array $x$, denoted $x_i$.
• Find array $y_i=f(x_i)$ for some function $f(x)$.
In [6]:
def f(x):
return x**2


## Use Python Lists¶

In [33]:
x = [1,2,3,4,5]

#------------ Method 1

y = []
for i in range(len(x)):
y.append(f(x[i]))

#------------ Method 2: list comprehension

y = [ f(x[i]) for i in range(len(x)) ]


## Use Numpy Arrays¶

In [34]:
import numpy as np
x = np.array([1,2,3,4,5])

#------------ Method 1

y = np.zeros(len(x))
for i in range(len(x)):
y[i] = f(x[i])

#------------ Method 2: list comprehension

y = np.array([ f(x[i]) for i in range(len(x)) ])


## More Examples¶

In [1]:
x = [5 for i in range(6)]
x

Out[1]:
[5, 5, 5, 5, 5, 5]
In [2]:
x = [i for i in range(6)]
x

Out[2]:
[0, 1, 2, 3, 4, 5]
In [3]:
x = [i**2 for i in range(6)]
x

Out[3]:
[0, 1, 4, 9, 16, 25]
In [12]:
x = [i for i in range(10) if i%2==0]    # same as x=[i for i in range(0,10,2)]
x                                       # but illustrates using an "if" condition

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