[Tutor] Would somebody kindly...

Dave Angel davea at davea.name
Wed Oct 29 13:29:56 CET 2014


"Clayton Kirkwood" <crk at godblessthe.us> Wrote in message:
> 
> 
> !-----Original Message-----
> !From: Tutor [mailto:tutor-bounces+crk=godblessthe.us at python.org] On
> !Behalf Of Dave Angel
> !Sent: Tuesday, October 28, 2014 6:34 PM
> !To: tutor at python.org
> !Subject: Re: [Tutor] Would somebody kindly...
> !
> !
> !>
> ! Explain this double speak(>:
> !>  [pair for pair in values if key == pair[0]]
> !
> !>  I understand the ‘for pair in values’. I assume the first  ‘pair’
> !> creates the namespace
> !
> !The namespace question depends on the version of Python. Python  2.x
> !does not do any scoping.
> !
> !But in version 3.x, the variable pair will go away.
> !
> !So please tell us the version you're asking about.
> 
> I am using 3.4.1.
> 

Have you somehow configured your email program to use exclamation
 points for quoting instead of the standard greater-than symbol?
 "!" instead of ">" ? If so, do you mind changing it
 back?

In 3.4.1, let's consider the following code.

thingie = 2
mylist = [(2,55), "charlie", [2, "item2", 12]]
x = [78 for item in mylist if item[0] == thingie]

What will happen in the list comprehension, and what will be the
 final value of x ?

First an anonymous list object will be created.  This eventually
 will be bound to x, but not till the comprehension is
 successfully completed. Next a locally scoped variable item is
 created.  This goes away at the end of the comprehension, 
 regardless of how we exit.

Next the 0th value from mylist is bound to item. It happens to be
 a tuple, but not from anything the comprehension
 decides.
Next the expression item [0] == thingie is evaluated.  If it's
 true, then the int 78 is appended to the anonymous
 list.

Now the previous group of actions is repeated for the 1th value of
 mylist. So now item is a string, and the zeroth character of the
 string is compared with the int 2. Not equal, so 72 doesn't get
 appended.

Similarly for the 2th item. The first element of that list is
 equal to 2, so another 72 is appended.

Now the anonymous list is bound to x.

print (x)
[72, 72]



-- 
DaveA



More information about the Tutor mailing list