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:
my_list = [1, 2, 3]
def my_func(list_as_argument):
for elem in list_as_argument:
print(elem)
my_func(my_list)
print(my_list)
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.
my_list = [1, 2, 3]
def my_func(list_as_argument):
list_as_argument[0] = 8
print(list_as_argument)
print(my_list)
my_func(my_list)
print(my_list)
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.
my_list = [1, 2, 3]
def my_func(list_as_argument):
new_list = list_as_argument.copy()
new_list[0] = 8
print(new_list)
print(my_list)
my_func(my_list)
print(my_list)
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]