In Python, what happens if several variables point to the same list and the dynamic array is relocated in memory?

Viewed 52

If I understand it correctly, in Python:

  • Lists are implemented as dynamic arrays.
  • If we assign a variable for a list to a new variable, then both variables point to the same list.

Please consider the following code in Python 3:

list1 = [1, 2, 3]
list2 = list1
list1.extend(list(range(10000000)))

By using 10000000 I am hoping that this causes the underlying dynamic array for list1 to be relocated in memory. After the relocation, do list1 and list2 still point to the same location on memory? (I think they do because print(len(list2)) gave me 10000003.) If so, how does Python do that? Does it keep track of how many variables are pointing to each object?

1 Answers

As you wrote list2 = list1 you made a reference to the list1, didn't made a copy of its values. Unless you make a copy of the list1 python treats your assignment as reference to list1 in order to keep computer's memory nice and neat. If you want you can copy the first list as the example below:

list1 = [1, 2, 3]
list2 = list1[:]

now you can work up with the lists separately.

Related