0

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

2
  • 1
    "[friend] is not defined": Yes, you define it right there in the for statement :) Commented Feb 3, 2015 at 8:56
  • In java if u type anything in between " " it is taken as STRING like wise in python if u type type between [] it is taken as list and between {} it is taken as tuples it is done in their compilation code to take it that was to reduce the burden on the user side Commented Feb 3, 2015 at 9:18

4 Answers 4

6
for friend in friends:
    print(friend)

is shorthand for

it = iter(friends)
while True:
    try:
        friend = next(it)
    except StopIteration:
        break
    print(friend)
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.