[Tutor] Python and Tuples
Steven D'Aprano
steve at pearwood.info
Sun Jan 30 10:47:08 CET 2011
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
More information about the Tutor
mailing list