0

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.

asked Jan 19, 2023 at 21:58
2
  • You should read it as for (x, y) in .... Commented Jan 19, 2023 at 22:00
  • 1
    No. Basically, its for <assignment target> in <iterable> is equivalent to <assignment targe> = <element> for each <alement> in the <iterable> Commented Jan 19, 2023 at 22:01

1 Answer 1

1

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)
answered Jan 19, 2023 at 22:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.