What is the 'number' variable in for loop?


#1

https://www.codecademy.com/courses/learn-python/lessons/python-lists-and-dictionaries/exercises/more-with-for?action=lesson_resume

I checked the solution code given by academy. I saw a variable named “number”. It was not defined anywhere before but it still worked perfectly. I don’t get it.

start_list = [5, 3, 1, 2, 4]
square_list = []

for number in start_list:
square_list.append(number ** 2)
square_list.sort()

print square_list


#2

number (the loop iterator) gets defined in the loop, python will assign all values in list to number in order


#3

Thanks. I get it. The variable (whatever it be) is defined in the loop and simultaneously values are assigned from the list using the 'in" syntax.


#4

yes, the variable/loop iterator isn’t defined in the loop, but the values aren’t assigned simultaneously. in the first iteration of the loop the first value of the list gets assigned to the loop iterator, then loop makes its iteration (doing everything that is inside the loop code block, then assigns the second item from list to iterator, executes the loop code block again and so on


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.