5.5. Making Shallow Copies of Lists

The slice syntax can easily create new strings or lists from existing ones. Enter the following into the interactive shell to see how it works:

>>> 'Hello, world!'[7:12] # Create a string from a larger string.
'world'
>>> 'Hello, world!'[:5] # Create a string from a larger string.
'Hello'
>>> ['cat', 'dog', 'rat', 'eel'][2:] # Create a list from a larger list.
['rat', 'eel']

The colon ( : ) separates the starting and ending indexes of the items to put in the new list you’re creating. If you omit the starting index before the colon, as in ‘Hello, world!’[:5] , the starting index defaults to 0 . If you omit the ending index after the colon, as in [‘cat’, ‘dog’, ‘rat’, ‘eel’][2:] , the ending index defaults to the end of the list.

If you omit both indexes, the starting index is 0 (the start of the list) and the ending index is the end of the list. This effectively creates a copy of the list:

>>> spam = ['cat', 'dog', 'rat', 'eel']
>>> eggs = spam[:]
>>> eggs
['cat', 'dog', 'rat', 'eel']
>>> id(spam) == id(eggs)
False

Notice that the identities of the lists in spam and eggs are different. The eggs = spam[:] line creates a shallow copy of the list in spam , whereas eggs = spam would copy only the reference to the list. But the [:] does look a bit odd, and using the copy module’s copy() function to produce a shallow copy of the list is more readable:

>>> # Pythonic Example
>>> import copy
>>> spam = ['cat', 'dog', 'rat', 'eel']
>>> eggs = copy.copy(spam)
>>> id(spam) == id(eggs)
False

You should know about this odd syntax in case you come across Python code that uses it, but I don’t recommend writing it in your own code. Keep in mind that both [:] and copy.copy() create shallow copies.