0

I'm messing around with Tuple unpacking and don't understand why I'm getting the result that I am.

I have a tuple list:

tup_list = [(1, 2, 3), (4, 5, 6)]

and when I do:

for a, b, c in tup_list:
    print(a)
    print(c)

it returns:

1
3
4
6

I mostly understand what's going on there, I established a variable for each item in the tuples and told it to print out certain ones. But when I do:

for item in tup_list:
    print(a)
    print(c)

it returns:

4
6
4
6

I have no idea what's happening here. Why am I getting four things returned but two of the are the same? How does it even know what to do if I haven't defined a and c?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 10
    That's using values for `a` and `c` from your previous loop. – jasonharper Nov 09 '21 at 20:32
  • 1
    Does this answer your question? [Scoping in Python 'for' loops](https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops) – mkrieger1 Nov 09 '21 at 20:33
  • 3
    `a` and `c` retain the last value you assigned to the... and you are simply repeatedly printing those values in a loop. "How does it even know what to do if I haven't defined a and c?" **you absolutely defined those variables**, right here: `for a, b, c in tup_list:` – juanpa.arrivillaga Nov 09 '21 at 20:34

0 Answers0