List Comprehensions
Learn about list comprehensions in Python.
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.
Press + to interact
#! /usr/bin/pythonimport numpy as npdef main():x = [5,10,15,20,25]# declare y as an empty listy = []# The not so good wayfor counter in x:y.append(counter / 5)print("\nOld fashioned way: x = {} y = {} \n".format(x, y))# The Pythonic way# Using list comprehensionsz = [n/5 for n in x]print("List Comprehensions: x = {} z = {} \n".format(x, z))# Finally, numpytry:a = x / 5except:print("No, you can't do that with regular Python lists\n")a = np.array(x)b = a / 5print("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 ...