Multiple tuples for one for statement

Daniel Cer Daniel.Cer at gmail.com
Sun Apr 24 23:31:51 EDT 2005


Harlin Seritt wrote:
> I have three tuples of the same size: tup1, tup2, tup3
> 
> I'd like to do something like this:
> 
> for a,b,c in tup1, tup2, tup3:
>    print a
>    print b
>    print c
> 
> Of course, you get an error when you try to run the pseudocode above.
> What is the correct way to get this done?

For something like this, you can use izip from itertools to package 
things up.

e.g. a working version of the code you posted using izip would be:

import itertools

tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
tup3 = (7, 8, 9)

for a,b,c in itertools.izip(tup1, tup2, tup3):
    print "a: %d b: %d c: %d" % (a, b, c)

This outputs:

a: 1 b: 4 c: 7
a: 2 b: 5 c: 8
a: 3 b: 6 c: 9

-Dan



More information about the Python-list mailing list