Loading...

Python Mutability

plate starts with tea, and water sits behind it. plate[0] = "soup" puts soup in place 0, so tea is no longer there. water stays in place 1. You still have two values. The end did not gain a value, and the end did not lose one.

print writes the values in the order they sit, brackets included. soup comes first because place 0 is the place you replaced. len(plate) is still 2. The first program does not print place 1 on its own line. The list line already shows water there.

soup takes place 0

python
plate = ["tea", "water"]
plate[0] = "soup"

print(plate)
print(len(plate))

The screen shows soup, then water, then the number 2. Place 1 did not move. tea is not in plate anymore.

same = plate adds a second name for the list you already have. A second list is not built. plate[1] = "soup" replaces water, and place 0 stays tea. The name same shows soup in place 1 as well. same[1] is soup too, even though the program prints the whole list instead of that place.

one list, two names

python
plate = ["tea", "water"]
same = plate
plate[1] = "soup"

print(plate)
print(same)

Both lines show tea, then soup. water is gone under both names. One replacement, one list. You did not build a copy on this page.

plate[2] = "bread" stops the program while plate only holds tea and water. Place 2 is not there yet. Replacing a place does not open a new place at the end. That line is not in the programs above.

plate = ["soup", "water"] is a different move. It builds a new list. The list you already had stays as it was for any name that still points at it. This page replaces a value inside the list you already have.

The next page builds a separate copy, so a later change through one name stays off the other. Here the two names are one list, and you only replace a value that is already in it.

Read the two screens

  1. What does the first program write, the list and then the number?
  2. After that program, what is in place 1?
  3. What do both prints in the second program write?
  4. Why does plate[2] = "bread" stop when plate only holds tea and water?

The length stays 2

In the first program soup takes the place of tea and the length stays 2, so the screen is soup, then water, then 2. water is still in place 1. In the second program both names show tea, then soup, because same and plate are one list and place 0 was left as tea. plate[2] = "bread" stops: that place is not there, and this replacement does not add one.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 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