Python Copying
bag.copy() takes the values that are in bag at that moment and puts them in a new list. Right now bag holds tea, then water, so the new list holds tea, then water. The name other is that new list. other is not bag.
Before any replacement, other place 0 is tea and other place 1 is water. The length is 2. The copy is a snapshot of this moment. It does not keep watching bag.
bag[0] = "soup" replaces tea only inside bag. other still starts with tea, and water stays in place 1 of both lists. Both lengths stay 2. The copy does not pick up the later replacement.
bag = ["tea", "water"]
other = bag.copy()
bag[0] = "soup"
print(bag)
print(other)
The first line is soup, then water. The second line is tea, then water. soup is only in bag. tea is still first in other. print writes each list with its brackets, so you can see the two lists side by side.
The other direction works the same way. other[1] = "bread" would put bread only in other. bag place 1 would stay water. This program does not take that step. It only changes bag after the copy.
bag[:] also builds a new list with the same values. That is the slice of the whole list, and the result is separate from bag. other = bag does not copy. Both names are the one list, so a later replacement shows under both names.
📊 Three ways to write it
| How | What you get |
|---|---|
| bag.copy() | a new list with the values as they are now |
| bag[:] | a new list with those same values |
| other = bag | not a new list; both names are the one list |
The name that keeps nothing back
If you write other = bag and then bag[0] = "soup", other shows soup as well. There was never a second list to keep tea. The program above uses copy(), so other keeps tea, then water.
The next page puts values into an order. This page does not reorder. tea stays in front of water in other because that was the order when you copied. soup is first in bag only because you replaced place 0 after the copy.
What stayed apart
- What does the program write, the first line and then the second?
- After the program, what is the first value in other?
- If you then set other place 1 to bread, what stays in bag at place 1?
- What does other = bag do that copy() does not?
tea stays in the copy
The screen is soup, then water, and then tea, then water. other still starts with tea. Both lengths are 2. bread in other would leave water in bag at place 1. other = bag is one list, so soup would show under both names. bag[:] is another new list with the same values. The next page orders values. It does not make this copy.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top