[Tutor] Would somebody kindly...

Alan Gauld alan.gauld at btinternet.com
Wed Oct 29 00:37:09 CET 2014


On 28/10/14 23:13, Clayton Kirkwood wrote:
> Explain this double speak(>:
>
> [pair for pair in values if key == pair[0]]

A list comprehension is a specific form of a more general
construction called a generator expression. Its specific
in that it creates a list, hence the [] around it.
The general shape of a generator expression is:

<result expression> for value in <iterator> if <condition>

and the comprehension version looks like

[ <result expression> for value in <iterator> if <condition> ]

The if condition part is optional in both cases.

This is syntactically equivalent to

aList = []
for value in iterator:
    if condition:
       aList.append(result expression)

Let's look at a specific example using literals:

[item for item in  [1,2,3,4,5] if item > 3]

The effect of which is the list [4,5]

So it acts as a filter that extracts the items in the inner
list that are greater than 3 (the if condition).

In your case I had proposed using a list of tuples(pairs)
like so:

values = [(1,2),(2,3),(3,4),(4,5)]

So the expression:

[pair for pair in values if 2 in pair]

will return [(1,2),(2,3)]

and the expression

[pair for pair in values if 2 == pair[0]]

will return [(2,3)] - the only pair with 2 in the first position

Now, coming back to your original question:

[pair for pair in values if key == pair[0]]

this returns the tuples that have the first element equal
to key - whatever the variable key happens to be.

PS.
For bonus points you can research how generator expressions
can encapsulate nested loops, but that's probably a step too
far for just now!

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list