[Tutor] Would somebody kindly...

Alan Gauld alan.gauld at btinternet.com
Wed Oct 29 10:49:59 CET 2014


On 29/10/14 04:33, Clayton Kirkwood wrote:

> !If we'd wanted the new list to contain double the original values we'd
> !write:
> !
> !   [ pair*2 for pair in values if key == pair[0] ]
>
> Ok, I am somewhat confused again. In the original example up above, it
> appears that the pair list or tuple gets overridden.

The point Cameron is making is that the first expression is completely 
arbitrary it does not even need to contain the variable used in the for 
loop. Here is an example of how to create a random number for each 
matching pair:

from random import random
...
random_list = [random() for pair in values if pair[0] == 2]

Notice the resultant list will contain one random number
for each pair found that has 2 as its first element.
Again the equivalent code:

random_list = []
for pair in values:
    if pair[0] == 2:
       random_list.append(random())

Another example, this time using numbers and a more complex
expression. Let's say we want the square root of all the
even numbers in a list:

from math import sqrt
roots = [sqrt(n) for n in [1,3,5,4,6,9,7,8,34,67,22] if n % 2 == 0]

yields:
[2.0, 2.449, 2.828, 5.830, 4.690]

So the expression that is put in the result is not necessarily the same 
as the value in the initial for loop, and in fact may be completely 
unrelated. It just happens to be a very common usage that we want
to extract a sub set of the values of a list.

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