12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

List Comprehensions: A First LookIn the prior section, we learned how to use range to change a list as we step across it:>>> L = [1, 2, 3, 4, 5]>>> for i in range(len(L)):... L[i] += 10...>>> L[11, 12, 13, 14, 15]This works, but as I mentioned, it may not be the optimal “best-practice” approachin <strong>Python</strong>. Today, the list comprehension expression makes many such prior usecases obsolete. Here, for example, we can replace the loop with a single expressionthat produces the desired result list:>>> L = [x + 10 for x in L]>>> L[21, 22, 23, 24, 25]The net result is the same, but it requires less coding on our part, and probably runssubstantially faster. The list comprehension isn’t exactly the same as the for loopstatement version because it makes a new list object (which might matter if there aremultiple references to the original list), but it’s close enough for most applications,and is a common and convenient enough approach to merit a closer look here.List Comprehension BasicsWe first met the list comprehension in Chapter 4. Syntactically, list comprehensions’syntax is derived from a construct in set theory notation that applies an operationto each item in a set, but you don’t have to know set theory to use them. In<strong>Python</strong>, most people find that a list comprehension simply looks like a backward forloop.Let’s look at the prior section’s example in more detail. List comprehensions arewritten in square brackets because they are ultimately a way to construct a new list.They begin with an arbitrary expression that we make up, which uses a loop variablethat we make up (x +10). That is followed by what you should now recognize as theheader of a for loop, which names the loop variable, and an iterable object (forxinL).To run the expression, <strong>Python</strong> executes an iteration across L inside the interpreter,assigning x to each item in turn, and collects the results of running items through theexpression on the left side. The result list we get back is exactly what the list comprehensionsays—a new list containing x+10, for every x in L.Technically speaking, list comprehensions are never really required because we canalways build up a list of expression results manually with for loops that appendresults as we go:272 | Chapter 13: while and for Loops

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!