Python 'for word in word' loop
Basic for a loop, I need help to understand how these loop words are:
word = "hello"
for word in word:
print word
Was the variable overwritten word=hello
with a word=h
just after starting the for loop? If so, how does it still go through all the letters in the word string?
Thanks in advance for the clarification.
source to share
Let's look at the bytecode:
>>> def so25807731():
... word = "hello"
... for word in word:
... print word
...
>>> import dis
>>> dis.dis(so25807731)
2 0 LOAD_CONST 1 ('hello')
3 STORE_FAST 0 (word)
3 6 SETUP_LOOP 19 (to 28)
9 LOAD_FAST 0 (word)
12 GET_ITER
>> 13 FOR_ITER 11 (to 27)
16 STORE_FAST 0 (word)
4 19 LOAD_FAST 0 (word)
22 PRINT_ITEM
23 PRINT_NEWLINE
24 JUMP_ABSOLUTE 13
>> 27 POP_BLOCK
>> 28 LOAD_CONST 0 (None)
31 RETURN_VALUE
Note that Python first grabs the iterator for string ( GET_ITER
) and then iterates over that, not the actual string ( FOR_ITER
).
Therefore, the original string is not required to "remember" what the characters were; it just uses the newly created iterator to do this. The value "old word
" is no longer used, so you can overwrite it without problems. This kind of logic explains why this code might work as well:
word = "llamas"
for character in word:
word = None
print character
source to share