For one and all - for , list and variables


#1


https://www.codecademy.com/en/courses/python-beginner-en-pwmb1/1/5?curriculum_id=4f89dab3d788890003000096#

my_list = [1,9,3,8,5,7]

for number in my_list:
print number * 2

Im just asking for a friend.....why is it that when you use a variable in a "for" statement.....like above "number" how does it reference the actualy number digits in the list if you havent declared the variable .

for instance previous to this excercise, to use a variable we would have to say

number = 20

in order to use it in a statement

then and only then

would:

print number * 2

work out:?

how does it know number is actually a digit within the list.

Replace this line with your code.


#2

The variable is sometimes called the iterator value placeholder. It is defined in the block as the temporary variable to hold the current value being iterated over.

It knows because the loop is operating on the list, and nothing else. All the values in the list will be iterated, one at a time.


#3

ok in order to test it i just used anything as the variable constant such as idontcarewhatthisis instead of "number" and it actually worked. it was confusing i thought number was syntax for a integer in this case. thanks bro


#4

When we set the loop up like so,

for number in number_list:

number will be a value from the list. When we set it up to iterate over a range,

for n in range(len(number_list):

n will be an index number, 0..len(number_list) - 1.

I like to call the first example a look-up loop, and the second, an index loop.


#5

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