Confused with a list... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Confused with a list...

I understand python but this has me baffled. Maybe it's because it's midnight and I'm tired but I can't keep to understand what's happening here. Why does the var for num1 get altered? num2 is assigned to a copy of num1. num2 changes the int at position 0 fine. But then if I print num1 it is also got the same starting value. Why is num1 getting changed? Please help explain this to me, thanks! https://code.sololearn.com/c8O0angSEUM3/?ref=app

27th Oct 2018, 10:46 PM
Jake S
Jake S - avatar
6 Answers
+ 5
Try num2 = num1[:]
28th Oct 2018, 2:45 AM
Anna
Anna - avatar
+ 4
you can change line 3 to num2 = num1.copy()
28th Oct 2018, 2:14 AM
David Ashton
David Ashton - avatar
+ 2
Jake S i explain this how this work. here num1 is a list means it point a list object.and you define num2 by using num1=num2 here num2 is the list ,means it is also a list object.and you know you define a num2 with the help of num1 means num2 is also point a same list object which num1 is point.now num1 and num2 has same point object if one is change then both will change because they has same point object. if you take real example let num1 and num2 is a human and num1 is write a programme with the help of laptop and num2 is also write a programme with the help of same laptop which is used by num1. if laptop is broke than they both don't work because they had same laptop if they had different laptops then only one is stop his work not both.
28th Oct 2018, 5:39 AM
Maninder $ingh
Maninder $ingh - avatar
+ 1
Also just by saying num2 = list(num1) will create a shallow copy and num2 can be added to without modifying num1. This way creates a reference to each child object in list one
28th Oct 2018, 12:49 AM
typhon humanoïde
typhon humanoïde - avatar
0
It is a lot to explain so read about deep and shallow copies. saying list2 = list1 creates a reference list2 is list1. https://code.sololearn.com/c1R4sAZsdlG6/?ref=app
27th Oct 2018, 11:15 PM
typhon humanoïde
typhon humanoïde - avatar
- 1
If you don't want to use: import copy, you can do this: list2=[] for i in list1: list2.append(i) list1[0]=5 # will not change list2
28th Oct 2018, 10:58 PM
Ehsan Tajik
Ehsan Tajik - avatar