Pass a List to a Function in Python (original) (raw)
Last Updated : 20 Dec, 2024
In Python, we can pass a list to a function, allowing to access or update the list's items. This makes the function more versatile and allows us to work with the list in many ways.
Passing list by Reference
When we pass a list to a function by reference, it refers to the original list. If we make any modifications to the list, the changes will reflect in the original list.
**Example:
Python `
def fun(l): for i in l: print(i,end=" ") # Iterates l = [1, 2, 3, 4] fun(l)
`
**Explanation:
- This function prints each element of the list_**l_.
- list_**l_ is passed, printing the numbers one by one.
By using *args (Variable-Length Arguments)
This allows us to pass a list to a function and unpack it into separate arguments. It is useful when we don't know the exact number of arguments the function will receive.
**Example:
Python `
def fun(*args): for i in args: print(i,end=" ") l = [1, 2, 3, 4, 5] fun(*l)
`
**Explanation:
- This function unpacks the list
l
into separate arguments. - It prints each element on the same line, separated by spaces.
Passing a copy
Shallow copy of a list creates a new list with the same elements, ensuring the original list remains unchanged. This is useful when we want to work with a duplicate without modifying the original.
Example:
Python `
def fun(l): l.append(6) a = [1, 2, 3, 4, 5] b = a.copy() # shallow copy of list fun(b) print(a) # Original list print(b) # Modified copy
`
Output
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6]
**Explanation:
- Shallow copy of
l
is created, keeping the original list unchanged. - Copied list is modified by appending
6
, while the original list remains the same.