0

I wanted to access the index of each element of iterable object. I found out on the internet that one can use enumerate function to generate tuples having index associated with respective element. But I have one confusion, how does python know which of the variables I chose in for loop is assigned the index and which variable is assigned the actual value of element?

I understand that this is not a problem just with enumerate function. Its a thing associated with for loop itself and I want to understand how it works. Here's an example:

for idx, val in enumerate(items):
    print("index is:"+str(idx)+" and value is:"+str(val))

How does python decide that "idx" gets the value of index of the two parts in tuple element and "val" gets the actual value part?

Is it something like the one on the left in "var1,var2" gets the index?

Can we make it so that "val" gets the index and "idx" gets the actual value without changing their order of appearance in " for idx,val in enumerate(items)"

4
  • 2
    Look up tuple unpacking. Its because enumerate returns positional tuple (the first element in the tuple is the index and the second element is the value). So it unpack the first value to idx and the second value to val. Swap your variables around and you will see this. Commented Jun 27, 2019 at 17:33
  • 1
    Can we make it so that "val" gets the index and "idx" gets the actual value without changing their order of appearance in " for idx,val in enumerate(items)" sure you can but why? Edit: This is one way, but it's totally useless: for idx, val in map(reversed, enumerate(items)). Don't do this. If you want val to get the index, change the order of the variables. Commented Jun 27, 2019 at 17:35
  • try doing in a shell a,b = (5,2). It works pretty much the same Commented Jun 27, 2019 at 17:39
  • @pault I asked just because I wanted to know if there's a way. I understand that switching the two around would obviously be unintuitive. Thanks for help!!! Commented Jun 27, 2019 at 17:39

1 Answer 1

3

Its tuple unpacking, the basic form is:

x, y = 2, 3
print(x, y) # Prints: 2 3

The enumerate call just returns the index as the first element and the value as the second:

a = ['a', 'b', 'c']
for index, val in enumerate(a):
    print(index, val) # Outputs 0 a --> 1 b --> 2 c

The naming is arbitrary:

a = ['a', 'b', 'c']
for b, c in enumerate(a):
    print(b, c) # Outputs 0 a --> 1 b --> 2 c

You can see this also with:

a = ['a', 'b', 'c']
for tup in enumerate(a):
    print(tup) # Outputs: (0, a) --> (1, b) --> (2, c)
Sign up to request clarification or add additional context in comments.

1 Comment

Is it bad that I ended up in Syntactial remorse? I am a beginner.

Your Answer

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.