I realize that i is a variable. So is soldier. I’m wanting to know what the variable is for–specifically, why this code is used instead of for soldier in soldiers.
enumerate can only be used on an object that can be iterated over. (i.e. a list,array,etc)
How it works:
array = ["Hello", "World", "!"]
for i in enumerate(array):
print i
This will print:
(0, “Hello”)
(1, “World”)
(2, “!”)
The function takes the list and pairs it with the iterator, making it a tuple. A tuple is immutable, meaning you cannot change whats inside.
Whats nice about enumerate is you can tell it what to start the iterator at. For example:
for i in enumerate(array, start = 1):
Will make the first line be (1, “Hello”) and so forth.
Now you should be able to piece everything together. The enumerate function will return a sequence¹ of tuples containing index and value pairs, then the for-loop will iterate over this sequence of tuples and unpack each tuple into two variables in each iteration.
¹ enumerate actually returns an iterator object, but that’s not really important for this topic as the for-loop consumes these seamlessly (just like any sequence).