# Why we do not have to use copy method for primitive data types?

For list we need to use copy method so that elements of one list get copied to other. If we do not use copy method, and use arithmetic operator = then both the List A = List B becomes same. So in case, we make any changes in List A it will be automatically reflected in List B(and that we do not want)
Why this behavior is different for primitive data types? Why we do not need to use copy method for primitive data types(it give desired results with arithmetic operator =)?

Let me first put you question in a code format

So the below shows what happens in case of list vs in case of integers (or for a matter any primitive data type)

``````# What happens in list
l1 = [1,2,3]
l2 = l1
l2.append(4) # l2 changed to [1,2,3,4]
print(l1)    # prints [1,2,3,4]

# What happens in integers (or any primitive data type)
a = 5
b = a
b = 3
print(a)    # prints 5 and does not change the value of a to 3
``````

In the first case changing l2 changes l1 because internally both l1 and l2 are pointing to the same memory location. So if you change l2 then l1 also changes.

In the second case till the code `b = a` both `a` and `b` were pointing to the same memory location (you can check by printing the memory location of `a` and `b` using id() function, if it is same then they are pointing to the same memory location)

But as soon as we did `b = 3`, this actually created a new variable `b` different from the earlier `b`.

This would also be true in the case of list as wellâ€¦For eg. if you execute below code

``````l1 = [1,2,3]
l2 = l1
l2.append(4) # l2 changed to [1,2,3,4]
print(l1)    # prints [1,2,3,4]
l2 = [1,2,3,4,5]
print(l1)   # prints [1,2,3,4] - i.e. l1 does not change
``````

here too till `l2 = l1`, both l1 and l2 were pointing to the same memory location. So modifying l2 modifies l1.

But as soon as we did `l2 = [1,2,3,4,5]` we created a new l2 variable in memory (this is not the same modifying the earlier l2 - one more important aspect is earlier l2 could be modified by appending because list are mutable but since integer or primitive date type are not mutable they could not be modified in the same way as l2)

1 Like

Understoodâ€¦ thanks for detail explanationâ€¦