I have tried to find an answer and sorry I can not seem to find one. in the following code:
friends = ['Bob','Luke','Ian', 'Frank']
for friend in friends:
print (friend)
How does Python know what friend is, it is not defined, all we have told python is that we have a variable (in this case a list of items) called friends.
I am trying to work it out in my head before trying to explain it to students. Thanks for any help
for friend in friends:
print(friend)
is shorthand for
it = iter(friends)
while True:
try:
friend = next(it)
except StopIteration:
break
print(friend)
That's how for
statement is implemented in Python. From the manual :
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed.
So friend
is not undefined, that's got defined by the for
statement.
Along side the other answers that explain nicety , and this fact that python assign the elements in list to name friend
in each iteration , you can use dis
module to see in detail :
>>> def fun():
... friends = ['Bob','Luke','Ian', 'Frank']
... for friend in friends:
... print friend
...
>>> import dis
>>> dis.dis(fun)
2 0 LOAD_CONST 1 ('Bob')
3 LOAD_CONST 2 ('Luke')
6 LOAD_CONST 3 ('Ian')
9 LOAD_CONST 4 ('Frank')
12 BUILD_LIST 4
15 STORE_FAST 0 (friends)
3 18 SETUP_LOOP 19 (to 40)
21 LOAD_FAST 0 (friends)
24 GET_ITER
>> 25 FOR_ITER 11 (to 39)
28 STORE_FAST 1 (friend)
4 31 LOAD_FAST 1 (friend)
34 PRINT_ITEM
35 PRINT_NEWLINE
36 JUMP_ABSOLUTE 25
>> 39 POP_BLOCK
>> 40 LOAD_CONST 0 (None)
43 RETURN_VALUE
As you can see on following line, python began to assignment the friend
and after each iteration it assigned again :
15 STORE_FAST 0 (friends)
The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter
friend
is bound in the for statement. At each iteration of the loop, the next element of the iterable gets bound to it. The iterable is friends
in your case.
The for syntax:
for element in iterable:
pass
loops over iterable
, binding each element to element
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.