< previous | Table of Contents | next > |
8.3 LIST OBJECTS IN MEMORY
The elements of a list are objects, and each object has a memory address. When you create a list, you create an object in memory that can store references to other objects, not the actual values themselves.
Thanks to this, multiple lists can refer to the same memory location, and changes to one would result in changes to another. Here’s an overview of what could happen and how to resolve this potential issue.
list1 = [1, 2, 3] list2 = list1 # Both list1 and list2 refer to the same list object in memory # Adding an element to the end of list1 list1.append(4) print(list1) # Outputs [1, 2, 3, 4] print(list2) # Outputs [1, 2, 3, 4] # an element via list2 list2[0] = 0 print(list1) # Outputs [0, 2, 3, 4] print(list2) # Outputs [0, 2, 3, 4]
In this case, list1 and list2 refer to the same object in memory. Modifying the list through either name affects the single underlying object.
We must create a copy to ensure that the two lists are independent.
list1 = [1, 2, 3] # Creating a copy of list1 through slicing, so that they refer to different memory addresses. list2 = list1[:] # Adding an element to the end of list1 list1.append(4) print(list1) # Outputs [1, 2, 3, 4] print(list2) # Outputs [1, 2, 3] # because list2 is an independent copy and not affected by changes to list1 # Editing an element in list2 list2[0] = 0 print(list1) # Outputs [1, 2, 3, 4] list1 remains unchanged print(list2) # Outputs [0, 2, 3] only list2 is changed
Here, list1[:] creates a new list object that is a copy of list1, meaning list1 and list2 refer to different objects in memory. Modifications to one list do not affect the other.
KEY THINGS TO REMEMBER
- Each element in a list has a distinct memory address. The list stores references to these addresses.
- When you assign one list to another
list2 = list1
, both variables refer to the same list object in memory. This also means that changes to one list will affect the other. list1[:]
creates a copy of the list which refers to a different memory address than the original list.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |