9.13. List arguments¶
When you pass a list to a function, the function gets a reference to the
list. If the function modifies a list parameter, the caller sees the
change. For example, delete_head
removes the first element from a
list and is used like this:
The parameter t
and the variable letters
are
aliases for the same object.
- ['a', 'b']
- myfun alters the state of the list object by removing the value at slot 0.
- ['b']
- myfun alters the state of the list object by removing the value at slot 0.
Q-2: What would print when the following code executes?
def myfun(lst):
del lst[0]
mylist = ['a', 'b']
myfun(mylist)
print(mylist)
It is important to distinguish between operations that modify lists and
operations that create new lists. For example, the append
method modifies a list, but the +
operator creates a new
list:
This difference is important when you write functions that are supposed to modify lists. For example, this function does not delete the head of a list:
def bad_delete_head(t):
t = t[1:] # WRONG!
The slice operator creates a new list and the assignment makes
t
refer to it, but none of that has any effect on the list
that was passed as an argument.
- True
- The slice operator creates a new list called "t", but that will not affect the list it was passed.
- False
- The slice operator creates a new list called "t", so it will not modify the original list.
Q-4: True or False. The following code block will not remove the first element from the list argument.
def deleting_first(lst):
lst = lst[1:]
An alternative is to write a function that creates and returns a new
list. For example, tail
returns all but the first element
of a list and leaves the original list unmodified. Here’s how it is used:
- +
- Using the + operator will create a new list, not modify the original.
- append
- The append method modifies the original list, rather than creating a new one.
- slice
- The slice operator creates a new list, rather than modifying the original.
Q-6: Which of the following list methods or operators will not create a new list when used.