I was trying something on this (lists & dictionaries). I could not understand the reason why there is an output instead of an error.
Screen Shot 2018-11-28 at 2.55.36 PM
I had changed the variable in the print function instead of “word” to “number”. I am trying to understand if the variable “number” itself has any defined function?
The last number only prints 7 * 2. It’s outside of the for loop. Is there any reason for only taking the last item of the list, I mean, why not the first? (It’s the last 14 in the output)
When i click this link it says “you do not have access to this page”. I am still curious why/how number is used as a variable to represent these numbers.
When you see the expression for number in my_list, for and in together comprise an operator: they work together to do something to an iterable. The lovely, seemingly circular definition of an iterable is “an object that works with for-in.” One that is a bit more intuitive is, “a sequence of objects that you can examine one-by-one.” Anyway, a list is an excelllent example of an iterable, and thats what we have here, in my_list.
So. for number in my_list: says:
Beginning with the first value (also might equally be called object, element or item) in the iterable to my right, my_list, assign that value to the variable whose name is between for and in, in this case, number. That variable, by the way, is called an iteration variable.
Then go to the indented code block following the colon ( : ), which might be called the for block or for suite, and execute that block of code, with the iteration variable, number, having the assigned value just discussed.
At the conclusion of the for block, return to the iterable, and assign the value of its second element to the iteration variable number. At this time, the first value is forgotten, as is any new value you, the coder, might have assigned it inside of the block.
Repeat the above process throughout the iterable, the variable number receiving in turn each value, until the final element is dealt with.
There being no more elements, pass control to the next level below for-in that is indented at the same or an outer level. (In Python, but not in all languages, number will still exist, retaining its final value.)