Passing a List to a Function in Python

You can pass a list as an argument of a Python function the same way as any other type and it will be the same type inside the function.

Take a look at the following example:

There is a list of three numbers. You can pass this list as an argument and display all its elements one by one:

1
2
3
[1, 2, 3]

If you print a list after the function execution, it will print the same numbers.

Because lists are mutable, when you pass a list as an argument, you create a reference to this list and not a copy.

If you print the list it will display numbers: 1, 2, 3.

After you modify this list, the modification will apply to the list outside the function because it was a reference and not a copy.

[1, 2, 3]
[8, 2, 3]
[8, 2, 3]

Creating a copy of a list

If you want to modify the list as a copy of the one inside parameter, you can use the copy function.

Now, if you run the code, the modification inside the function doesn’t apply to the my_list list, because the function operates on a copy and not on the original object.

[1, 2, 3]
[8, 2, 3]
[1, 2, 3]