Beginner 5 min
Lists, indexes, and copies
A list keeps values in order and can change as your program runs.
How it works
After copy = values.copy(), picture two rows of list slots. Appending to copy changes its row alone. If one slot points to an inner list, both rows can still point to that same inner object. The right kind of copy depends on which level you expect to change.
Walk through an example
The first value in [4, 8, 12] is at index 0. values[-1] finds the last item. values.append(16) adds a new value at the end.
What to watch for
Writing other = values gives the same list another name. Use values.copy() for a separate outer list. Inner lists are still shared.
Code example
values = [4, 8, 12]
copy = values.copy()
copy.append(16)
print(values)
print(copy)Check your understanding
What does a contain after the last line?
See the example and explanation
- Worked example
- Given
a = [1, 2]; b = a; b.append(3) - Answer
[1, 2, 3]
Both names refer to the same list. The append changes that one list.