[Tutor] [Q] list and loop

Kirby Urner urnerk@qwest.net
Mon, 26 Nov 2001 21:05:47 -0800


>
>I think there must be an elegant way in python using for loop, but I
>couldn't figure it out.
>Thanks in advance.
>
>YJ

Yeah, zip is what you want:

   >>> list1 = [1,2,3,4]
   >>> list2 = [10,20,30,40]
   >>> zip(list1,list2)
   [(1, 10), (2, 20), (3, 30), (4, 40)]

A way to do it with list comprehension would be:

   >>> [(list1[i],list2[i]) for i in range(len(list1))]
   [(1, 10), (2, 20), (3, 30), (4, 40)]

In a classic loop:

   >>> def mkzip(list1,list2):
           output = []
           for i in range(len(list1)):
              output.append((list1[i],list2[i]))
           return output

   >>> mkzip(list1,list2)
   [(1, 10), (2, 20), (3, 30), (4, 40)]

And then there's the fine map solution already posted:

   >>> map(None,list1,list2)
   [(1, 10), (2, 20), (3, 30), (4, 40)]

All of these assume your lists are the same length.
If not, you have more work to do.

Kirby