Home > OS >  When a value of a sliced list "copy" is overwritten, the original list does not change. Wh
When a value of a sliced list "copy" is overwritten, the original list does not change. Wh

Time:12-02

I come from R and am trying to get a better grip on mutability. Below is code, the first two parts of which I think I understand (see comments). I do not understand the third part.

#1. Refering to same instance with two variable names
listOrig = [i for i in range(1001, 1011)]
listCopy = listOrig
listOrig[0]=999
listOrig == listCopy #Returns True, because both variable names actually refer
#to the same instance, ergo still containing the same values
listOrig[0] is listCopy[0] #Same instance 999, the id is also the same as a 
#consequence

#2. Refering to same part of original list through slicing
listSlice = listOrig[0:5] 
listOrig[0] is listSlice[0] #Returns True, analogous to above
a = 999
listOrig[0] == a #True because it's the same value or number
listOrig[0] is a #False because they are different instances with different IDs
  
#3. WHAT I DO NOT UNDERSTAND: changing the sliced copy does not affect the original list
listOrig
listSlice
listSlice[0] = 1001
listOrig[0] is listSlice[0] #Different number, thus also obviously different ID

CodePudding user response:

I am going to post an answer just because I think this is better explained with diagrams.

Suppose you create a list list_1 containing the numbers 1, 2 and 3.

list_1 = [1,2,3]

list_1

Then you assign the list to a new variable.

list_2 = list_1

It is another reference to the same original list.

list_2

Alternatively, suppose you take a slice of your list.

list_3 = list_1[:]

It is a new list with references to the same objects.

list_3

So if you reassign an element in the new list, it does not affect the original.

list_3[0] = 4

changed list_3

CodePudding user response:

As is said in the comments, the slice is a copy of the original list. It currently (when the values are same) refers to same memory address and hence the id (with e.g. id-function) is the same and listOrig[0] is listCopy[0] is True.

Below example formulates this: even if you set two different integer variables b and c to be the same value, their ids are same. However, if you change the value of b, the value of c does not change. You can also check print(id(listSlice), id(listOrig[0:5])) from your example which shows, that the ids of the slice-variable and the original slice are different

a = 1
b = 2
c = 2

print(id(a))
print(id(b))
print(id(c))

print(b is c)

The output would be e.g.

2770111129904

2770111129936

2770111129936

True
  • Related