6. Copy vs reference

Assigning a list to another variable does not copy it:

Both names point to the same list object, so a change through one name is visible through the other. This is called an alias.

To get an independent list, copy it. Two common ways:

list[:] is a slice from the beginning to the end, and list.copy() is a method with no arguments. Both return a new list: changing the copy does not change the original.

Coming from JavaScript? list[:] and list.copy() are like [...list]: a shallow copy. Assigning alias = original shares the same list, just like assigning an array in JS.

#01

Alias the same list

Create original = [1, 2, 3]. Create alias by assigning original to it; do not copy it. Change the element at index 0 of alias to 100. Print original, then print alias.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Copy with a full slice

Create original = [1, 2, 3]. Copy it into copied with a full slice ([:]). Change the element at index 0 of copied to 100. Print original, then print copied.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Copy with the copy method

Create original = [1, 2, 3]. Copy it into copied with .copy(). Change the element at index 0 of copied to 100. Print original, then print copied.

Print exactly:

Create a free account to save your progress and unlock chapter 2.