Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Python High Performance

You're reading from   Mastering Python High Performance Learn how to optimize your code and Python performance with this vital guide to Python performance profiling and benchmarking

Arrow left icon
Product type Paperback
Published in Sep 2015
Publisher
ISBN-13 9781783989300
Length 260 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Fernando Donglio Fernando Donglio
Author Profile Icon Fernando Donglio
Fernando Donglio
Arrow right icon
View More author details
Toc

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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image