Search⌘ K

List Comprehensions

Explore the fundamentals of Python list comprehensions and their practical use in processing lists efficiently. Understand how they compare with NumPy arrays for mathematical operations and learn when to use each approach for scientific and engineering applications.

List comprehension: an old method

An essential part of Python is list comprehension. This will come up repeatedly in examples seen online, so we’re learning about them separately. List comprehension is technically not a part of NumPy, but we’ll introduce it here for a supplementary explanation of the lesson.

The following was the old standard for list comprehensions. Let’s look at the code and then we’ll discuss it in detail.

Python 3.8
#! /usr/bin/python
import numpy as np
def main():
x = [5,10,15,20,25]
# declare y as an empty list
y = []
# The not so good way
for counter in x:
y.append(counter / 5)
print("\nOld fashioned way: x = {} y = {} \n".format(x, y))
# The Pythonic way
# Using list comprehensions
z = [n/5 for n in x]
print("List Comprehensions: x = {} z = {} \n".format(x, z))
# Finally, numpy
try:
a = x / 5
except:
print("No, you can't do that with regular Python lists\n")
a = np.array(x)
b = a / 5
print("With Numpy: a = {} b = {} \n".format(a, b))
return "With Numpy: a = {} b = {} \n".format(a, b)
if __name__ == "__main__":
main()

We’re importing numpy in line 3 as np (this means we don’t have to type numpy every time, which is a typical Python pattern).

Next, we’ll initialize x with five values and y as an empty list in lines 6–8 in the above code ...