2

So i copied using copy.copy which is shallow but if i change the value in one the value in the other won't get changed.

import copy
a=[1,2,3,4,5]
b=copy.copy(a)
print id(a[0])==id(b[0])

now i get true as output.Since the address of a[0] and b[0] is same then if i change the value of one the other must also change.

b[0]=55
print[a]
print[b]

Output:

[1,2,3,4,5]
[55,2,3,4,5]

So why is it like that?

Danra
  • 9,546
  • 5
  • 59
  • 117
ashwin murthy
  • 59
  • 1
  • 1
  • 6

4 Answers4

7

id(a[0])==id(b[0]) returns True because you're comparing the identities of the integers (1 in this case) not the lists, and integers are interned (as an implementation detail) within the range of -5 to 256 as explained here.

copy.copy returns a shallow copy of the list so id(a) == id(b) returns False.

You can see a visualization of this I made on Python tutor.

Community
  • 1
  • 1
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
4

A shallow copy of a list is not the same list. A shallow copy of a list creates another list but links to the original contained elements. A deep copy instead copy also the elements. So, a and b point to the same elements, but are different list.

shallow copy vs deep copy

So when you change b you are not changing a. What you want is just this:

b = a
b[0] = 55
print(a)      # [55, 2, 3, 4, 5]
print(b)      # [55, 2, 3, 4, 5]
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
2

you get same id because integers are immutable in python. There is only one 1 (or any integer). If you think about it, you will see that anyway it does not make sense to keep multiple values of a constant integer.

for example

a = 1
b = 1
id(a) == id(b)
True

Here although a and b are completely independent variables, since they store the same integer values their ids are the same

You can modify the values of a and b independently as you would expect.

b = 2
id(a) == id(b)
False

Now if we have a third variable, say c

c = 2
id(c) == id(b)
True

This behaviour actually has nothing to do with shallow/deep copy. As another example, using dictionaries

d = {'a': 1}
e = {'c': 1}
id(d['a']) == id(e['c'])
True
sid-m
  • 1,504
  • 11
  • 19
1

copy.copy(a) create another list, it does not have the same address. Only the content are the same (different from deepcopy that recreate list and content).

>>> a=[1,2,3,4,5]
>>> b=a
>>> id(a) == id(b) #True

>>> a=[1,2,3,4,5]
>>> b=copy.copy(a)
>>> id(a) == id(b) #False
Cyrbil
  • 6,341
  • 1
  • 24
  • 40