5

I have a tuple of lists. Each list in the tuple has the same number of elements. How can I iterate over it in a for loop

Ex:

tupleList = ([1,2,3], ['label1', 'label2', 'label3'])
for (val, label) in <something>:
    print val, label

Should output:

1, label1
2, label2
3, label3

NOTE: This list of tuples could contain more than two lists.

PS: For those who have opted this as a duplicate, please check the responses for the correct solution. It's different from iterating through two separate lists.

Vishal
  • 3,178
  • 2
  • 34
  • 47
  • 3
    Can your `tupleList` contain more than 2 lists? – kuro Apr 07 '17 at 09:45
  • Yes, more than 2 lists is possible. But the number of lists present, I would know in advance. – Vishal Apr 07 '17 at 10:48
  • You can apply a loop like this - `for i in range(1, len(tupleList), 2)`. Inside that you can apply `zip` on `tupleList[i]` and `tupleList[i+1]` like mentioned in the answers. – kuro Apr 07 '17 at 10:56
  • as you may note, zipping each individual element of the tuple separately is the longer solution. Whereas @Roelant's solution offers a shorter alternative. – Vishal Apr 07 '17 at 11:04

3 Answers3

9

You can use zip and flatten the tuple_list with the asterix syntax.

tuple_list = ([1,2,3], ['label1', 'label2', 'label3'])
for val, label in zip(*tuple_list):
     print(val, label)

If you're still in python 2.7:

import itertools
tuple_list = ([1,2,3], ['label1', 'label2', 'label3'])
for val, label in itertools.izip(*tuple_list):
     print val, label
Roelant
  • 4,508
  • 1
  • 32
  • 62
0

Here is a simple solution using zip

tupleList = ([1,2,3], ['label1', 'label2', 'label3'])
for (val, label) in zip(tupleList[0],tupleList[1]):
    print(val, label)
Sunit Deshpande
  • 126
  • 2
  • 5
0

Try this,

In [3]: for v,k in zip(*tupleList):
   ...:     print v,k
   ...:     
1 label1
2 label2
3 label3
Rahul K P
  • 15,740
  • 4
  • 35
  • 52