0

The assignment operator appears to work differently for lists than it does for integers:

>>> list1 = [1,2,3,4,5]
>>> newlist1 = list1
>>> print(id(list1))
140282759536448
>>> print(id(newlist1))
140282759536448
>>> newlist1.append(6)
>>> print(id(newlist1))
140282759536448
>>> print(list1)
[1, 2, 3, 4, 5, 6]
>>> print(newlist1)
[1, 2, 3, 4, 5, 6]

The Assignment Operator works in a similar way with integers:

>>> int1 = 1
>>> newint1 = int1
>>> print(id(int1))
140282988331248
>>> print(id(newint1))
140282988331248

But modifying one of the integers creates a new ID:

>>> newint1 = newint1 + 1
>>> print(id(newint1))
140282988331280
>>> print(id(int1))
140282988331248

Why does modifying a list not create a new ID?

As well, how would you create a new ID for a list?

  • 1
    Well, you modify the list, but you replace the integer. – Klaus D. Nov 25 '22 at 16:15
  • 1
    your attribut is just a name, so you can affect the same reference to two names. If you want to create a new list you can copy the first one by adding `[:]`. Integers (str and some others) are treated diffently to optimize time and space memory. You can find more information in this thread: https://stackoverflow.com/questions/55206114/how-reference-works-in-python-integer-vs-list-in-list-both-value-are-same-why – Adrien Derouene Nov 25 '22 at 16:22

2 Answers2

0

You should use newlist1 = list1.copy() because when you do newlist1 = list1 you are not creating new list you are referencing the same list

Yafaa Ben Tili
  • 176
  • 1
  • 7
0

In Python, when you assign a list to a new variable, you will only pass the address of the list to it. That is why the id()function return the same value.

If you want to actually copy the list you have to use the copy() function:

initList = ["a", "b", "c"]
print(id(initList))

copiedList = initList.copy()
print(id(copiedList))
Jonas
  • 31
  • 4