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.
We'll cover the following...
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.
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 ...