Search code examples
pythonlistmemorymutable

Does adding a list unassigned to a variable to another variable pointing to a different list create a new list object?


Here's what I mean:

x = [1, 2, 3]
y = x
y = y + [4]

It's to my understanding that the variable y points to the variable x, which stores the list object [1, 2, 3]. At the second line of code, both x and y store the same id. In the last line of code, we are changing what the variable y stores. Will adding the list [4] to y create a new list object containing an int object for 4? I'm pretty sure both x and y still point to the same id since lists are mutable, I just need confirmation on the [4]. Is a new list and int object created?


Solution

  • Never mind, I got it! I had it wrong, a new object is created for y in the third line! it's the list [1, 2, 3, 4]. The variable x still refers to the list [1, 2, 3]. Adding [4] is similar to the .extend() function in python in which a new int object would be created for 4, but not a new list object to contain that int!