Play Home Contribute GitHub Join Us Discourse Staff Members GitHub Contribution Guides Team

Advanced for-looping


On the Library Tactician level, I encountered a for-loop that looked like nothing I had seen before:

for i, soldier in enumerate(soldiers):
    commandSoldier(soldier, i, len(soldiers))

What do the “i” and “enumerate” mean? I couldn’t find anything that explains them.



What is the programming language that you are using. (JavaScript, Python, etc.)


I’m using Python. Why?


The I is the varibable. I’ll look into what everything else is.


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 takes each element in the list and pairs it with the index of the element.


Is its purpose, then, to run through two arrays at once (e.g. an array of soldiers and an array of points to which to move)?


Yes, I believe it is.


In that case, I think I have this figured out. Thanks much for your help, @ChronistGilver!


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.


Nice explanation about the built-in enumerate function, @Zhio!

for idx, soldier in enumerate(['Skywalker', 'Vader']):

Is equivalent to:

for idx, soldier in [(0, 'Skywalker'), (1, 'Vader')]:

Now, what hasn’t been well explained yet is sequence unpacking. It allows assigning values from a sequence to variables:

idx, soldier = (0, 'Skywalker') 
print idx # 0
print solider # 'Skywalker'

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