What can we do with each item in a list in a for loop?
Answer
For loops are great for doing something to every item in a list. So good, in fact, that they built this handy syntax into the language itself! In other programming languages, doing this for item in list is not so simply written!
In this exercise, that something we want to do each time is to multiply the item by 2. But you could do whatever you wanted to each item each time it loops.
To demonstrate how item becomes the next item in the list after every time it loops, take a look at the code below:
my_list = [1, 2, 3, 4]
for item in my_list:
print item # displays the current item in the list
I was playing around with for loops so I can get more comfortable with them outside of the exercise.
I tried to use the variable that was defined in the for loop outside of it and it did work but the answer it printed to the console does not make sense. I was curious as to what it would print since it was coming from a list of 6 integers, but it only printed a single number. Any reason that this was the answer I got?
Ya i realized after where I was making the mental error. I thought it may print all of the numbers from my_list when I typed print str(number), but realized it only printed the last value from the list which makes sense.
Variable names are arbitrarily chosen and hopefully reflect what the object represents. The floor is wide open. Generally, we use a name with the clearest meaning.
Above we have a list of numbers, so, number is an apt choice since it describes the value it references. The elements can just as easily be referred to as items, so item is okay, though ambiguous since item could be any object, not just a number.
Bottom line, variables are defined when we give then something to reference (set them with an assignment). Clarity (clear meaning) helps both us and other readers understand and follow our code.
It is a string representation of the number given in the argument. If you check its type you’ll find that it is now a string, but still the character, ‘7’.