[Tutor] Would somebody kindly...

Cameron Simpson cs at zip.com.au
Wed Oct 29 08:34:04 CET 2014


On 28Oct2014 21:33, Clayton Kirkwood <crk at godblessthe.us> 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. In this one right
>above, once again, the list gets overwritten again, but what is being
>doubled?, each part of the tuple?

A different try. Sometimes it helsp to see a concrete example. Do this at the 
command line:

   Python 3.4.2 (default, Oct  9 2014, 11:02:09)
   [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
   Type "help", "copyright", "credits" or "license" for more information.
   >>> values = [ (1,2), (3,4) ]
   >>> values
   [(1, 2), (3, 4)]

   >>> result = [ pair for pair in values if pair[0] == 3 ]
   >>> result
   [(3, 4)]

   >>> result = [ pair[1] for pair in values if pair[0] == 3 ]
   >>> result
   [4]

You're thinking, I think, that "pair" a tuple which is overwritten with a copy 
of each tuple from the list in turn. It is not.

The list comprehension above is equivalnt to a for loop starting:

   for pair in values:

During this loop, the _name_ "pair" becomes a direct reference to each tuple 
from the list "values". No tuples are copied or changed.

So if the list looks like this:

   values --> [
                 (1, 2),
                 (3, 4)
              ]

During the first loop iteration, "pair" gets bound to the first tuple, like 
this:

   values --> [
     pair -----> (1, 2),
                 (3, 4)
              ]

See? One list, two tuples, with "values" bound to the list, and "pair" bound to 
the first tuple.

On the second loop iteration, "pair" is bound to the second tuple (the arrow 
moves). No copying.

The result of the list comprehension is the first expression (eg "pair[1]") 
evaluated for each iteration (where the "if" expression is true). So, the 
expression in the examples above is true only for the second tuple. So the 
expression "pair[1]" is only used for that tuple. And so the final result is a 
single element list with a "4", taken from the second tuple.

Maybe this makes things clearer.

Cheers,
Cameron Simpson <cs at zip.com.au>

Draw little boxes with arrows.  It helps.       - Michael J. Eager


More information about the Tutor mailing list