Python from zero: two names can share one list
Assigning a list to a second name does not copy it. list() does. The program adds a muffin to the ticket and prints ['latte'] ['latte', 'muffin'].
Zoe is one of GoByte's characters. This post was drafted by AI agents in Zoe's voice, then fact checked, run and edited by the GoByte team.
ticket = kitchen does not copy a list. It makes a second name for the same list. Append through either name and both names see it. A ticket that adds a muffin must not rewrite the kitchen's list. The tip: call list(kitchen) when the ticket needs its own list.
Assignment copies the name, not the list#
ticket = kitchen does not copy the list. It makes a second name for the same object, so ticket.append("muffin") is visible through kitchen. list(kitchen) allocates a new list and copies the references that were in kitchen. Appending to ticket then changes only ticket. The copy is shallow: if the elements were themselves lists, those inner lists would still be shared. This program's elements are strings, which this lesson does not mutate, so the shallow copy is a real split. The print shows ['latte'] and ['latte', 'muffin'].
- kitchen['latte']
- ticket['latte', 'muffin']
kitchen = ["latte"]
ticket = list(kitchen)
ticket.append("muffin")
print(kitchen, ticket)
['latte'] ['latte', 'muffin']
list() is a new list#
kitchen is a list with one drink. list(kitchen) builds a new list with the same items and stores it in ticket. ticket.append("muffin") changes ticket only. print shows ['latte'] and then ['latte', 'muffin'].
Replace list(kitchen) with ticket = kitchen and run it again. Both names print ['latte', 'muffin']. Nothing threw. The bug is a kitchen list that changed when you thought you still had the original menu. This shows up when a function appends to an argument. The caller's list changes too, because the parameter is another name for that list.
Copy when the next owner should be alone#
Pass list(items) into a function that appends, if the caller still needs the old list. If sharing is what you want, ticket = kitchen is the right line, and it is cheaper. Know which one you wrote. The next lesson puts a number on an object and changes it through a method, on purpose.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.