List Copying and References

Example 1: List Assignment

What is the output of the following code?

a = [1, 2, 3]
b = a
b[0] = 99
print(a)
print(b)

You might think the output is:

[1, 2, 3]
[99, 2, 3]

However, the actual output is:

[99, 2, 3]
[99, 2, 3]

This happens because when we do b = a, we are not creating a new copy of the list. Instead, both a and b refer to the same list in memory. Therefore, modifying b also affects a.

Here is a visualization of what happens in memory:

To make an actual copy of the list, you can use one of the following methods:

# Method 1: Using the list() function
b = list(a)

# Method 2: Use slicing
# A slice is a list containing copied elements 
# from the original list
b = a[:]

# Method 3: Using the copy() method
b = a.copy()

Example 2: Function Argument Passing

What happens when you pass a list to a function?

Let’s begin by studying the following code:

def fun(a):
    a[0] = 42
    print("Inside fun:", a)

a = [1, 2, 3]
fun(a)
print("After fun:", a)

The output will be:

Inside fun: [42, 2, 3]
After fun: [42, 2, 3]

Why did modifying a in the function modify a outside the function? Shouldn’t there be two separate a’s, one in the global frame and another local to fun? The answer is yes, but both a’s are references to the same list.

If you visualize the execution of the code, you will see that sending a list to a function passes a reference to that list, not a copy of the list itself.

Example 3: Reassigning vs. Modifying

Let’s now look at the following example:

def half(a):
    a = a[:len(a) // 2]
    print("Inside the function:", a)

a = [1, 2, 3, 4, 5, 6]
half(a)
print("Outside the function:", a)

The output will be:

Inside the function: [1, 2, 3]
Outside the function: [1, 2, 3, 4, 5, 6]

The statement a = a[:len(a) // 2] creates a new list that is half the size of the original list and reassigns the local variable a to refer to this new list. This does not affect the original list outside the function.

To understand the difference between modification and reassignment better, consider the following example that combines both:

Visualize the execution to see how the list is modified and how reassignment works.


© Ibrahim Albluwi. · Last updated: