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.

... if x % 2 == 0:... res.append(x)...>>> res[0, 2, 4]All of these use the modulus (remainder of division) operator, %, to detect even numbers:if there is no remainder after dividing a number by two, it must be even. Thefilter call is not much longer than the list comprehension here either. However, wecan combine an if clause, and an arbitrary expression in our list comprehension, togive it the effect of a filter and a map, in a single expression:>>> [x ** 2 for x in range(10) if x % 2 == 0][0, 4, 16, 36, 64]This time, we collect the squares of the even numbers from 0 through 9: the for loopskips numbers for which the attached if clause on the right is false, and the expressionon the left computes the squares. The equivalent map call would require a lotmore work on our part—we would have to combine filter selections with map iteration,making for a noticeably more complex expression:>>> map((lambda x: x**2), filter((lambda x: x % 2 == 0), range(10)))[0, 4, 16, 36, 64]In fact, list comprehensions are more general still. You can code any number ofnested for loops in a list comprehension, and each may have an optional associatedif test. The general structure of list comprehensions looks like this:[ expression for target1 in sequence1 [if condition]for target2 in sequence2 [if condition] ...for targetN in sequenceN [if condition] ]When for clauses are nested within a list comprehension, they work like equivalentnested for loop statements. For example, the following:>>> res = [x + y for x in [0, 1, 2] for y in [100, 200, 300]]>>> res[100, 200, 300, 101, 201, 301, 102, 202, 302]has the same effect as this substantially more verbose equivalent:>>> res = []>>> for x in [0, 1, 2]:... for y in [100, 200, 300]:... res.append(x + y)...>>> res[100, 200, 300, 101, 201, 301, 102, 202, 302]Although list comprehensions construct lists, remember that they can iterate overany sequence or other iterable type. Here’s a similar bit of code that traverses stringsinstead of lists of numbers, and so collects concatenation results:>>> [x + y for x in 'spam' for y in 'SPAM']['sS', 'sP', 'sA', 'sM', 'pS', 'pP', 'pA', 'pM','aS', 'aP', 'aA', 'aM', 'mS', 'mP', 'mA', 'mM']List Comprehensions Revisited: Mappings | 357

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

Saved successfully!

Ooh no, something went wrong!