Working with Lists in Functions

CS 65/STEM 280: Introduction to Computer Science I

Lists as arguments and return values

You can normally use lists as arguments and return values just fine, though there's a slight nuance to be aware of.

In [1]:
def double_val(param):
    param = param * 2

x = 4
double_val(x)
print(x)
4
In [2]:
def double_list(param):
    param[0] = param[0] * 2

x = [4]
double_list(x)
print(x)
[8]

Why does this happen?

Big objects like collections are really stored in a different part of memory which is referenced by the variable name.

When you pass one of these objects as an argument, the parameter is really a copy of the reference, not the value itself.

Small objects like ints and floats really do get copied to the parameter.