[Python] Iterate over elements in tuple (Python)

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to programming, and for practice reasons, I am 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:

    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 this error:


    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. What is the correct way to unpack the 3 elements?

    Continue reading...

Compartilhe esta Página