Copying lists

Indeed, the full slice is an important idiom for copying a list. Recall that assigning references never copies an object, but rather merely copies a reference to an object:

>>> t = s
>>> t is s
True

We deploy the full slice to perform a copy into a new list:

>>> r = s[:]

And confirm that the list obtained with the full slice has a distinct identity:

>>> r is s
False

Although it has an equivalent value:

>>> r == s
True

It's important to understand that although we have a new list object which can be independently modified, the elements within it are references to the same objects referred to by the original list. In the event that these objects are both mutable and modified (as opposed to replaced) the change will be seen in both lists.

We show this full-slice list copying idiom because you are likely to see it in the wild, and it's not immediately obvious what it does. You should be aware that there are other more readable ways of copying a list, such as the copy() method:

>>> u = s.copy()
>>> u is s
False

Or a simple call to the list constructor, passing the list to be copied:

>>> v = list(s)

Largely the choice between these techniques is a matter of taste. Our preference is for the third form using the list constructor, since it has the advantage of working with any iterable series as the source, not just lists.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset