简体   繁体   中英

How multiple variables work in for loop in python with enumerate?

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)"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM