List comprehension and generators

List comprehension is a special construct provided by Python to generate lists by writing in the way a mathematician would, by describing its content instead of writing about the way the content should be generated (with a classic for loop).

Let's see an example of this to better understand how it works:

#using list comprehension to generate a list of the first 50 multiples of 2
multiples_of_two = [x for x in range(100) if x % 2 == 0]

#now let's see the same list, generated using a for-loop
multiples_of_two = []
for x in range(100):
  if x % 2 == 0:
    multiples_of_two.append(x)

Now, list comprehension is not meant to replace for loops altogether. They are a great help when dealing with loops that, like the earlier one, ...

Get Mastering Python High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.