Iterate over elements in tuple (Python)
Asked Answered
M

1

5

I am new in programming, and for practice reasons, I trying to iterate over elements in a tuple and after give to each different element an index.

I have a problem iterating over tuples, here is my code:

p.s: I use enumerate in order to keep an index for each tuple.

myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
for tup in myList:
    for x, y, z in enumerate (tup):
        print(x, y, z)

But i get the this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-72-cfb75f94c0bb> in <module>
     17 myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
     18 for tup in myList:
---> 19     for x, y, z in enumerate (tup):
     20         print(x, y, z)

ValueError: not enough values to unpack (expected 3, got 2)

I gave 3 elements to unpack and I got anyway that error. Which is the correct way to unpack tuples of 3 elements?

Mullock answered 18/6, 2021 at 16:56 Comment(1)
what are you trying to do with enumerate (tup)? What do you think enumerate does?Royall
B
9

I gave 3 elements to unpack and I got anyway that error. Which is the correct way to unpack tuples of 3 elements?

The problem is that the for loop is basically unpacking the tuple for you already. For example:

myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
for tup in myList:
    for x in tup:
        print(x)

To use enumerate() correctly, you need to unpack the two elements that are returned from it:

myList = [(5, 7, 24), (0, 6, 10), (0, 3, 24), (1, 3, 100), (7, 10, 15)]
for tup in myList:
    for i, x in enumerate(tup):
        print(i, x)

If instead, you want the index of each tuple in the parent list, you need to enumarate(myList) in the outer loop:

for i, (x, y, z) in enumerate(myList):
    print(i, x, y, z)
Bicorn answered 18/6, 2021 at 17:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.