I'm a complete beginner to python (from C/C++) I'm just practicing on python from few days and when I observed the behavior of the below lines, I'm confused.
#Integer case
num1 = 1
num2 = num1
print num1, num2
num1 += 1
print num1, num2
#List case
list1 = [1,2,3,4,5]
list2 = list1
print list1,list2
list1[2:2] = [0,0,0]
print list1, list2
This piece of code gave me the following result:
1 1
2 1
[1,2,3,4,5] [1,2,3,4,5]
[1,2,0,0,0,3,4,5] [1,2,0,0,0,3,4,5]
Here,the change of value of num1
is not reflected in num2
. But the change in list1
is reflected in list2
. I'm confused with this behavior, please clarify (I'm a beginner, explanation from a beginner point of view is greatly appreciated)
edited:
and how can I achieve a copy of list1
(without actually creating a reference)?
Take a case where I have the list1
(I need it unchanged in the later part of my code) and also list2
which has other data apart from 'list1' (Want to add data over list1
data). How't that copying possible?