简体   繁体   中英

list python; why get different results?

friends = ['Masum','Pavel','Sohag']
print(friends[1]) # this one gives me the result 'Pavel'

for friends in friends:
    print('Happy new yers,', friends)

print(friends[1]) # Why this one give me the result o

Try friend in friends . You kinda overwriting friends with same name of iterator.

When you write:

for friends in friends:

you re-assign the label friends to the items in this array. After loop completion, the array does not have any name, and hence is lost. However, the label friends will store the last value of that array. eg ( -> means ' points to ')

Before iteration: friends -> array
Ist iteration: friends -> 'Masum'
2nd iteration: friends -> 'Pavel'
3rd iteration and after loop completion: friends -> 'Sohag'

Note that there is only one variable now with value 'Sohag'. Every other variable/array is lost.

Because you used the name friends for the list and for the string, so your variable friends was changed from ['Masum','Pavel','Sohag'] to "Sohag" at the end of your for.

To correct this just change your for to: for friend in friends

Do not use the same variable name as the list for the iteration:

friends = ['Masum','Pavel','Sohag']

for friend in friends:
    print('Happy new yers,', friend)

# At this point friend will be the last one while friends will still be the list you assigned

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM