Question

I am a beginner in python and I find this about mutabilty quite confusing and non intuitive. Given a list:

lst = [[1, 2, 3], [4, 5, 6]]

And trying to change the list within a for-loop.

for i in lst:
    i = "test"

I understand that this does not change the list. But:

for i in lst:
    i[1] = "test"

I was surprised that referring to the sublist led to following outcome:

[[1, 'test', 3], [4, 'test', 6]]

I tried to understand with a visualizer but I don't get it. Would anybody please explain this in plain words? Thank you.

Was it helpful?

Solution 2

Assignment (which is what the = operator does) assigns a value to a name.

i is a variable name in the local namespace. At the time it runs inside the for loop, it refers to a list. By assigning a string to it, you cause the name to no longer refer to a list, but instead refer to the string. The list is unaffected -- the only thing that changes is the value associated with the name.

i[1] is a name that specifies a specific location inside one of the two lists, depending on what i is set to at the time. By assigning a string to it, you cause the name to no longer refer to the object that previously occupied that space inside the list (an integer, 2 or 5 depending on the list) and instead refer to the string. The integer is unaffected -- the only thing that changes is the value associated with the name.

So in each case, assignment is doing the same thing -- it's making a name refer to a new thing instead of the old thing it referred to. The difference is that the second case is a special name in that it refers to a property of a mutable object.

OTHER TIPS

In the first case, you simply have a copied reference to the element.

i ---> lst[n]

In the latter case, you are dereferencing the reference, and changing data (not in a copy):

i[i] ---> lst[n][i]

Therefore assigning to i[n] will point to the actual mutable object, not a copy of it.

for does not make copies of each element it yields. As such, the yielded object retains all the properties of the original (since it is the original), including mutability.

since for loop in case of string is called in different way like for i in lst:

it means if lst is list or array of string then i is referenced to the value of x[i] directly that is why in first case result was "test " two times because length of "lst" was just 2

while in second case i[1] means i ------lst[i] i[1]--------`-lst[i][1] means first value equal lst[0][1]---[1,'test',3] second value equal lst[1][1]--[4,'test',6]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top