1

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])

3 Answers 3

3

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])]
Sign up to request clarification or add additional context in comments.

1 Comment

you really saved the day. Thank you, how can i get in touch so you can help me with another thing I have a problem with
1

You can use a list comprehension:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.