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.

94 Lists<br />

If a function returns a list, it returns a reference <strong>to</strong> the list. For example, tail<br />

returns a list that contains all but the first element of the given list:<br />

def tail(list):<br />

return list[1:]<br />

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

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

>>> rest = tail(numbers)<br />

>>> print rest<br />

[2, 3]<br />

Because the return value was created <strong>with</strong> the slice opera<strong>to</strong>r, it is a new list.<br />

Creating rest, and any subsequent changes <strong>to</strong> rest, have no effect on numbers.<br />

8.14 Nested lists<br />

A nested list is a list that appears as an element in another list. In this list, the<br />

three-eth element is a nested list:<br />

>>> list = ["hello", 2.0, 5, [10, 20]]<br />

If we print list[3], we get [10, 20]. To extract an element from the nested list,<br />

we can proceed in two steps:<br />

>>> elt = list[3]<br />

>>> elt[0]<br />

10<br />

Or we can combine them:<br />

>>> list[3][1]<br />

20<br />

Bracket opera<strong>to</strong>rs evaluate from left <strong>to</strong> right, so this expression gets the three-eth<br />

element of list and extracts the one-eth element from it.<br />

8.15 Matrices<br />

Nested lists are often used <strong>to</strong> represent matrices. For example, the matrix:<br />

1 2 3<br />

4 5 6<br />

7 8 9

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

Saved successfully!

Ooh no, something went wrong!