Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List assignment in python

I have a code like below,when i print the list1 and list2 it shows same elements but i have added the 9 after the assignment of existing list1 to list2 so it should not show 9 in list2.

list1=[1,2,3,4]
list2=list1
list1.insert(4,9)
print(list1)
print(list2)

please clear my doubt.

like image 405
hieko Avatar asked Jun 22 '26 04:06

hieko


1 Answers

In python, a variable name is a reference to the underlying variable. Both list1 and list2 refer to the same list, so when you insert 9 into that list, you see the change in both. You need to make an explicit copy (using the copy module, slice notation list2 = list1[:], or some other method) if you want them to be distinct.

like image 114
Daniel H Avatar answered Jun 23 '26 17:06

Daniel H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!