Tuesday 6 August 2019

Python Data Structure: Difference between two types of for-loop in python?



I was thinking this question should be asked on SO, but I was not able to find it somehow(Let me know in the comment section if there was one, i will delete this post)



It has came to my attention that when we do list replacement, it only works if we are loop through the list by index. Why?



myList = ['a','b','c','d','e']
for item in myList:
if item == 'a':
item = 's'

print("First loop:",myList) //It prints ['a','b','c','d','e']


for i in range(len(myList)):
if myList[i] == 'a':
myList[i] = 's'
print("Second loop:",myList) //It prints ['s','b','c','d','e']


I have tried to read the python control flow documentation: https://docs.python.org/3/tutorial/controlflow.html but it does not really answer my question.



Answer



In each iteration of the first loop, the variable item gets assigned to each item in the list. When the if condition is satisfied, you then only reassign the variable item to 's', but that does not change the content of the list.



In the second loop, you are re-assigning the contents of my_list, as you are assigning the ith item to 's' with the line.



    myList[i] = 's'


Consider also a simpler example:




    myList = ['a', 'b', 'c']
item = myList[0] # assign item to 'a'
item = 's' # re-assign item variable to 's', does not change list
myList[0] = 's' # change the content of the first item in the list


Also have a look at this: Python : When is a variable passed by reference and when by value?


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...