Passing a list to a function in Python

You can pass a list as an argument of 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:

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.

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.