Variable used to represent each item


#1

Why is the variable used to represent each item in the list below called number?

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

for item in my_list:
  print 2 * number

The word number doesn’t show up anywhere else in the code. I tried using different variables such as num and item. Does this happen because the items in the list are all of type integer or float (ie: numbers)?


FAQ: Learn Python: Python Lists and Dictionaries - For One and All
FAQ: Learn Python: Python Lists and Dictionaries - For One and All
#2

The variable to use would be the one defined in the for statement signature line, item. It is intended as a temporary variable to hold, in turn, each value in the list.

print 2 * item

or,

for number in my_list:
    print 2 * number

#3

Thanks for the reply. I realized that I forgot to change the number to item on line 4 in

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

for item in my_list:
  print 2 * number

After I changed them both, it worked just fine.


#4

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