Nice Steve, No one does it better. Weldone. Sent from my BlackBerry wireless device from MTN
-----Original Message----- From: Steven D'Aprano <st...@pearwood.info> Sender: tutor-bounces+delegbede=dudupay....@python.org Date: Sun, 30 Jan 2011 20:47:08 To: <tutor@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@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor