ZpfSysn
ZpfSysn

Reputation: 889

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.

Upvotes: 0

Views: 99

Answers (4)

Fabian Ying
Fabian Ying

Reputation: 1254

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?

Upvotes: 1

araraonline
araraonline

Reputation: 1562

For an example of why the first loop doesn't work, check this:

myList = ['a','b','c','d','e']
item = myList[0]
item = 's'

# this is an example equivalent to what the first loop does
# the values in myList remain unchanged

And an example equivalent to the second loop:

myList = ['a','b','c','d','e']
myList[0] = 's'

# the first value in myList is changed to 's'

Upvotes: 1

SuperStew
SuperStew

Reputation: 3054

In your first for loop, "item" is just a variable that gets assigned to whichever list item the loop has got to. Reassigning the variable doesn't affect the list. In the second loop, you directly change the list item, which is why it shows up when you print the list.

Upvotes: 2

André Nasturas
André Nasturas

Reputation: 113

In the first loop, the line item = 's' only changes the value of the locale variable item inside the loop, which is updated in each iterations by the next value in the list. It is not a reference to the list itself.

Upvotes: 3

Related Questions