Noob SWEbot
Noob SWEbot

Reputation: 1

Python: Unpacking elements of nested lists in a for-loop

I have the following code:

queries = [[0, 3], [2, 5], [2, 4]]
for x, y in queries:
    ...

I understand that this is utilizing "tuple unpacking"

I don't quite understand how the "x" and "y" in the for-loop point to the first and second elements (respectively) of each nested list.

To me, the "for x" reads as "for every element in the outer list" and the "y" part is the nested list at each index. In other words, I'm reading this as X points to each index in "queries" and Y points to the element at that index (so the nested/inner lists).

How is the loop going into each nested list and setting the first element to X and the second element to Y?

I've since read up on tuple unpacking, list comprehension as well as viewing related examples but I have an improved understanding of tuple unpacking but not quite the issue I brought up.

Upvotes: 0

Views: 160

Answers (1)

Michael Cao
Michael Cao

Reputation: 3609

Think of (x,y) as a single entity that grabs the nested list and then is subdivided into x and y. The below code is equivalent and maybe spells it out better:

queries = [[0, 3], [2, 5], [2, 4]]
for query in queries:
    x, y = query
    print(x,y)

Upvotes: 1

Related Questions