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 :
def f(x):
return x**2

Use Python Lists¶

In :
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 :
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 :
x = [5 for i in range(6)]
x
Out:
[5, 5, 5, 5, 5, 5]
In :
x = [i for i in range(6)]
x
Out:
[0, 1, 2, 3, 4, 5]
In :
x = [i**2 for i in range(6)]
x
Out:
[0, 1, 4, 9, 16, 25]
In :
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:
[0, 2, 4, 6, 8]