[Tutor] Would somebody kindly...

Steven D'Aprano steve at pearwood.info
Wed Oct 29 13:04:18 CET 2014


On Tue, Oct 28, 2014 at 04:13:19PM -0700, Clayton Kirkwood wrote:
> Explain this double speak(>:
> 
> [pair for pair in values if key == pair[0]]

Translated to a regular for-loop:

result = []
for pair in values:
    if key == pair[0]:
        result.append(pair)


It iterates over the sequence `values`, extracting something called 
`pair`. If the first item of `pair` == key, then the pair is placed in 
the resulting list.

py> values = [ ('a', 1), ('b', 2), ('a', 5), ('c', 7)]
py> key = 'a'
py> [pair for pair in values if key == pair[0]]
[('a', 1), ('a', 5)]


-- 
Steven


More information about the Tutor mailing list