Book Image

Mastering Python High Performance

Book Image

Mastering Python High Performance

Overview of this book

Table of Contents (15 chapters)

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, are creating a list. However, they aren't particularly recommended for those for loops that you write because of their side effects. This means you're not creating a list. You're most likely calling a function inside it or doing some other...