[Tutor] Python and Tuples

delegbede at dudupay.com delegbede at dudupay.com
Sun Jan 30 11:07:02 CET 2011


Nice Steve,
No one does it better. 
Weldone. 
Sent from my BlackBerry wireless device from MTN

-----Original Message-----
From: Steven D'Aprano <steve at pearwood.info>
Sender: tutor-bounces+delegbede=dudupay.com at python.org
Date: Sun, 30 Jan 2011 20:47:08 
To: <tutor at python.org>
Subject: Re: [Tutor] Python and Tuples

Becky Mcquilling wrote:
> I'm fairly new to python and I am trying to do some math with tuples.
> 
> If I have a tuple:
> 
> t =( (1000, 2000), (2, 4), (25, 2))
> I want to loop through and print out the results of the multiplying the two

Start with a basic loop through the objects in the tuple:

 >>> t = ( (1000, 2000), (2, 4), (25, 2) )
 >>> for pair in t:
...     print(pair)
...
(1000, 2000)
(2, 4)
(25, 2)

This walks through the outer tuple, grabbing each inner tuple (a pair of 
numbers) in turn. So we *could* (but won't -- keep reading!) write this:

for pair in t:
     x = pair[0]  # grab the first number in the pair
     y = pair[1]  # and the second number
     print(x*y)


and that would work, but we can do better than that. Python has "tuple 
unpacking" that works like this:

 >>> pair = (23, 42)
 >>> x, y = pair
 >>> print(x)
23
 >>> print(y)
42



We can combine tuple unpacking with the for-loop to get this:

 >>> for x,y in t:
...     print(x*y)
...
2000000
8
50



-- 
Steven

_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list