- 5.1 Introduction
- 5.2 Lists
- 5.3 Tuples
- 5.4 Unpacking Sequences
- 5.5 Sequence Slicing
- 5.6 del Statement
- 5.7 Passing Lists to Functions
- 5.8 Sorting Lists
- 5.9 Searching Sequences
- 5.10 Other List Methods
- 5.11 Simulating Stacks with Lists
- 5.12 List Comprehensions
- 5.13 Generator Expressions
- 5.14 Filter, Map and Reduce
- 5.15 Other Sequence Processing Functions
- 5.16 Two-Dimensional Lists
- 5.17 Intro to Data Science: Simulation and Static Visualizations
- 5.18 Wrap-Up
5.7 Passing Lists to Functions
In the last chapter, we mentioned that all objects are passed by reference and demonstrated passing an immutable object as a function argument. Here, we discuss references further by examining what happens when a program passes a mutable list object to a function.
Passing an Entire List to a Function
Consider the function modify_elements, which receives a reference to a list and multiplies each of the list’s element values by 2:
In [1]: def modify_elements(items): ...: """"Multiplies all element values in items by 2.""" ...: for i in range(len(items)): ...: items[i] *= 2 ...: In [2]: numbers = [10, 3, 7, 1, 9] In [3]: modify_elements(numbers) In [4]: numbers Out[4]: [20, 6, 14, 2, 18]
Function modify_elements’ items parameter receives a reference to the original list, so the statement in the loop’s suite modifies each element in the original list object.
Passing a Tuple to a Function
When you pass a tuple to a function, attempting to modify the tuple’s immutable elements results in a TypeError:
In [5]: numbers_tuple = (10, 20, 30) In [6]: numbers_tuple Out[6]: (10, 20, 30) In [7]: modify_elements(numbers_tuple) ------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-9339741cd595> in <module>() ----> 1 modify_elements(numbers_tuple) <ipython-input-1-27acb8f8f44c> in modify_elements(items) 2 """"Multiplies all element values in items by 2.""" 3 for i in range(len(items)): ----> 4 items[i] *= 2 5 6 TypeError: 'tuple' object does not support item assignment
Recall that tuples may contain mutable objects, such as lists. Those objects still can be modified when a tuple is passed to a function.
A Note Regarding Tracebacks
The previous traceback shows the two snippets that led to the TypeError. The first is snippet [7]’s function call. The second is snippet [1]’s function definition. Line numbers precede each snippet’s code. We’ve demonstrated mostly single-line snippets. When an exception occurs in such a snippet, it’s always preceded by ----> 1, indicating that line 1 (the snippet’s only line) caused the exception. Multiline snippets like the definition of modify_elements show consecutive line numbers starting at 1. The notation ----> 4 above indicates that the exception occurred in line 4 of modify_elements. No matter how long the traceback is, the last line of code with ----> caused the exception.