06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

8.13 List parameters 93<br />

>>> b[0] = 5<br />

>>> print a<br />

[1, 2, 3]<br />

As an exercise, draw a state diagram for a and b before and after this<br />

change.<br />

8.13 List parameters<br />

Passing a list as an argument actually passes a reference <strong>to</strong> the list, not a copy of<br />

the list. For example, the function head takes a list as an argument and returns<br />

the first element:<br />

def head(list):<br />

return list[0]<br />

Here’s how it is used:<br />

>>> numbers = [1, 2, 3]<br />

>>> head(numbers)<br />

1<br />

The parameter list and the variable numbers are aliases for the same object.<br />

The state diagram looks like this:<br />

__main__<br />

head<br />

numbers<br />

list<br />

[ 1, 2, 3 ]<br />

Since the list object is shared by two frames, we drew it between them.<br />

If a function modifies a list parameter, the caller sees the change. For example,<br />

deleteHead removes the first element from a list:<br />

def deleteHead(list):<br />

del list[0]<br />

Here’s how deleteHead is used:<br />

>>> numbers = [1, 2, 3]<br />

>>> deleteHead(numbers)<br />

>>> print numbers<br />

[2, 3]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!