O'Reilly logo

Mastering Python High Performance by Fernando Doglio

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required