Python Peculiarity: Copying Lists Using Slice

Being an experienced developer but a n00b to Python, I’ve decided to pick up an excellent book named “Effective Python” by Brett Slatkin.

The book contains a heap-load of useful information about different idioms in the Python language and echo-system, and a few peculiar gems such as:

Copying Lists Using Slice

Python’s slice syntax lets us create subsets of lists by specifying different indices, for example:

A subset excluding the first element

>> a_list = [1, 2, 3]
>>> a_list[1:]
[2, 3]

A subset excluding the last element

>> a_list = [1, 2, 3]
>>> a_list[:-1]
[1, 2]

Now, being developers we’re very likely to use this feature with variables:

>> n = 1
>>> a_list = [1, 2, 3]
>>> a_list[-n:]

But see what happens if n is replaced by zero, making our start index -0:

>> n = 0
>>> a_list = [1, 2, 3]
>>> a_list[-n:]
[1, 2, 3]

Our list has been copied in its entirety!


One thought on “Python Peculiarity: Copying Lists Using Slice

  1. you can copy the entire list using y = x[:]

    which is good, because if you just use y = x instead, you really just create a shortcut with a different name. changes to the contents of one may affect the other. if you want an independent copy, [:] is one tool to help get one.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s