0%

Lists · practice

When Two Names Share a List

A can change in place. That creates a surprise when you the same list to a second name: assignment does not automatically take a snapshot.

Try it

Both names show the new item. The assignment shared_plan = weekend did not copy the list. It gave one list a second name.

Now that the surprise is visible, we can choose the solution deliberately.

Make a separate list when changes should stay separate

Call .copy() when you need an independent outer list:

Try it

Now the lists begin with equal items but can change independently. .copy() earns its place because we have seen the problem it solves.

Assignment makes weekend and shared_plan point to one changed list, while copy() gives separate_plan an independent list.

The exercise at the end of this lesson builds both relationships in one program. After append(), the one shared has changed, so the change shows through either name, while the separate copy stays as it was.

This distinction explains behavior that can otherwise feel surprising:

Try it

Changing alias changes original because those names refer to the same list. The copied list keeps 10 as its first item.

What does this code print?

colors = ["red", "blue"]
other = colors
saved = colors.copy()
other.append("green")
print(colors)
print(saved)

For the lists of and numbers here, a useful question is: “Should these two names see the same future changes?” If yes, assignment may be right. If no, make a copy.

The word outer matters: .copy() makes a new list, but it does not also copy objects stored inside that list. If an item is itself a list, both outer lists still refer to that same inner item. This is called a shallow copy. The strings and numbers in our examples cannot be changed in place, so replacing an item in either outer list leaves the other list alone.

Task

Complete the program so it creates both kinds of relationship:

  • Make shared_plan another name for the existing weekend .

  • Make separate_plan a separate copy.

  • Keep the provided append operation.

  • Replace the first item in separate_plan with "cycle".

  • Print all three lists.

The appended item should appear through weekend and shared_plan, but not in separate_plan.

Once it runs, press Step in the editor toolbar and move through the program with Next, watching the panel. When weekend.append("cook") runs, weekend and shared_plan change together, because they are two names for one list. separate_plan does not move. That is the whole idea of this lesson, visible in one moment.