+ 1
Why is .pop() behaving like this? (Python)
I don't understand why the original list "strg" is being modified. I applied .pop() to its copy "g", yet "strg" is also changed (I wanted to keep "strg" unchanged ). strg=["a","a","b","b"] g=strg g.pop(1) #applied to "g" only print(strg) print(g) The output is ["a","b","b"] and ["a","b","b"]
6 ответов
+ 7
Alvaro Vallejos ,
you can find some more explanations in the file about creating *copies* from a list by using an assignment, using function copy() or function deepcopy ().
https://code.sololearn.com/cQPb1y2A5quw/?ref=app
+ 5
Try this
strg=["a","a","b","b"]
g=strg.copy()
g.pop(1) #applied to "g" only
print(strg)
print(g)
#Explanation
The copy() method returns a copy of the specified list.
+ 5
Alvaro Vallejos This is a strange, but intended, behaviour of mutable objects in Python.
When you assign a mutable object - like a list or a dictionary - to multiple variables, they don't get copies of the object. They get references to the same object. So, if you have:
a = <Some list>
b = a
Both a and b have the same object. So, changing either variable actually changes the object referenced by both.
For fun:
a = [1, 2]
b = a # Same object
c = a.copy() # Copy to another object
a.append(3) # What changes?
print(b)
print(c)
+ 4
Thank you!
I will look up this method.
+ 3
Thank you everybody, very helpful
+ 3
The issue in more detail explained here (code for reading, run for seeing the examples play out).
https://code.sololearn.com/c89ejW97QsTN/?ref=app