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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

92 Lists<br />

8.11 Aliasing<br />

Since variables refer <strong>to</strong> objects, if we assign one variable <strong>to</strong> another, both variables<br />

refer <strong>to</strong> the same object:<br />

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

>>> b = a<br />

In this case, the state diagram looks like this:<br />

a<br />

b<br />

[ 1, 2, 3 ]<br />

Because the same list has two different names, a and b, we say that it is aliased.<br />

Changes made <strong>with</strong> one alias affect the other:<br />

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

>>> print a<br />

[5, 2, 3]<br />

Although this behavior can be useful, it is sometimes unexpected or undesirable.<br />

In general, it is safer <strong>to</strong> avoid aliasing when you are working <strong>with</strong> mutable objects.<br />

Of course, for immutable objects, there’s no problem. That’s why <strong>Python</strong> is free<br />

<strong>to</strong> alias strings when it sees an opportunity <strong>to</strong> economize.<br />

8.12 Cloning lists<br />

If we want <strong>to</strong> modify a list and also keep a copy of the original, we need <strong>to</strong> be able<br />

<strong>to</strong> make a copy of the list itself, not just the reference. This process is sometimes<br />

called cloning, <strong>to</strong> avoid the ambiguity of the word “copy.”<br />

The easiest way <strong>to</strong> clone a list is <strong>to</strong> use the slice opera<strong>to</strong>r:<br />

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

>>> b = a[:]<br />

>>> print b<br />

[1, 2, 3]<br />

Taking any slice of a creates a new list. In this case the slice happens <strong>to</strong> consist<br />

of the whole list.<br />

Now we are free <strong>to</strong> make changes <strong>to</strong> b <strong>with</strong>out worrying about a:

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

Saved successfully!

Ooh no, something went wrong!