Tuples ? How to ?

Remco Gerlich scarblac at pino.selwerd.nl
Tue Apr 3 06:43:23 EDT 2001


Mickael ABBAS <abbasmicNOSPAM at utc.fr> wrote in comp.lang.python:
> Just a question:
> How to make a imbricated tuple as, for example:
> ((1,10),(2,20),(3,30))
> when we don't know the size and we have only the two lists:
> [1,2,3] and
> [10,20,30]
> I tried with a loop (for...) but I obtain only something like that:
> (((1,10),(2,20)),(3,30))

The easiest way is to make a list, then convert that to a tuple.

Now in 2.0, there is a new function zip() that takes two lists and makes
tuples of them element wise, so

>>> zip([1,2,3], [10,20,30])
[(1,10),(2,20),(3,30)]

And you only need to turn that into a tuple:
>>> tuple(zip([1,2,3], [10,20,30]))
((1,10),(2,20),(3,30))

In older Python versions, tuple(map(None, list1, list2)) does the same
thing, except if your first and second list have different length; zip()
will make a list with length of the shortest, map(None,...) makes it equal
to the longest, filling it in with 'None'.

-- 
Remco Gerlich



More information about the Python-list mailing list