Advanced for-looping


#1

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.

Thanks!


#2

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


#4

I’m using Python. Why?


#5

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


#6

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.


#7

enumerate takes each element in the list and pairs it with the index of the element.


#8

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


#9

Yes, I believe it is.


#10

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


#11

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.


#12

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