don
don

Reputation: 186

Python: Loop through multiple lists and create a tuple

I have 2 lists of data and I would like to create a tuple for this lists that looks like

ttuple=(1,[4,6,counter])

listA=[1,2,3,4,5,6,7,8,9]
listB=[3,4,5,7,8,9,0,-4,5]
counter=0
for i in range(len(listA)):
     for lista in listA:
         for listb in listB:
              data=(i,[lista,listb,counter])
              myList.append(data)
print(data)

Only the last value is printed. Can someone point to me what I am doing wrong. Its supposed to print tuple list of 9 values like the following. The last number is a counter that increments by 1

(0,[1,3,0),(1,[2,4,0]),(2,[3,5,0])

All i get is the following:

(0,[1,1]),(0,[1,1]),(0,[1,1]), (1,[2,2]),(1,[2,2]),(1,[2,2])

Upvotes: 1

Views: 1903

Answers (3)

agrinh
agrinh

Reputation: 1905

There's two issues with the code you provided (that I can find anyways). Biggest of which is the fact that you produce len(listA) ** 2 * len(listB) elements! You do not have to iterate over listA and listB instead use the index i to access the elements in both lists. Another issue is that myList is not defined (but I assume you just forgot that).

Here's a more fun way of solving this:

from itertools import izip
n = len(min(listA, listB))
result = list(enumerate(izip(listA, listB, xrange(n))))
print(result)

This will however give you tuples everywhere, to match the exact output just do:

from itertools import izip
n = len(min(listA, listB))
result = list(enumerate(list(item) for item in izip(listA, listB, xrange(n))))
print result

Upvotes: 0

ebarr
ebarr

Reputation: 7842

You can use a list comprehension:

output = [(ii,[b,c,counter]) for ii,(b,c) in enumerate(zip(listA,listB))]

Upvotes: 1

shaktimaan
shaktimaan

Reputation: 12092

You can use enumerate and zip in conjunction to get what you want:

>>> listA=[1,2,3,4,5,6,7,8,9]
>>> listB=[3,4,5,7,8,9,0,-4,5]
>>> output = []
>>> for i, a in enumerate(zip(listA, listB)):
...     output.append((i, [a[0], a[1], 0]))
...
>>> output
[(0, [1, 3, 0]),
 (1, [2, 4, 0]),
 (2, [3, 5, 0]),
 (3, [4, 7, 0]),
 (4, [5, 8, 0]),
 (5, [6, 9, 0]),
 (6, [7, 0, 0]),
 (7, [8, -4, 0]),
 (8, [9, 5, 0])]

Upvotes: 3

Related Questions