Why is .pop() behaving like this? (Python) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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"]

28th Feb 2023, 4:46 PM
Alvaro Vallejos
Alvaro Vallejos - avatar
6 Answers
+ 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
28th Feb 2023, 7:57 PM
Lothar
Lothar - avatar
+ 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.
28th Feb 2023, 5:07 PM
◦•●◉✿𝕀ℕ𝔻𝕀✿◉●•◦
◦•●◉✿𝕀ℕ𝔻𝕀✿◉●•◦ - avatar
+ 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)
28th Feb 2023, 11:41 PM
Emerson Prado
Emerson Prado - avatar
+ 4
Thank you! I will look up this method.
28th Feb 2023, 6:14 PM
Alvaro Vallejos
Alvaro Vallejos - avatar
+ 3
Thank you everybody, very helpful
1st Mar 2023, 8:54 AM
Alvaro Vallejos
Alvaro Vallejos - avatar
+ 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
1st Mar 2023, 12:12 PM
HonFu
HonFu - avatar