Understanding Python List Slicing

Lists are one of Python’s main data structures. A list can contain many data types and can also contain other lists. Strings can also be treated as lists when you want to slice and dice them! The same rules will apply.

One way to access the data in a list is known as ‘slicing’. To new users, slicing can can be confusing and difficult to use. Understanding the concept is actually simple and will become second nature after you have used it a few times.

Python lists can be complicated as you need but, in my opinion, if a list is littered with many different data types, it is probably time you started thinking of how to simplify your data structure!

Creating a list is fairly straight forward.

myList = []

The empty list is defined by using square brackets ‘[]’. To populate the list with data, we merely add items between the brackets and separate them with a comma. The list that will be used for these slicing exercises is defined by:

myList = [1,2,3,4,5,6,7,8,9,10]

Python lists are zero indexed. This means that the first element of the list is actually element 0. A graphical representation of our list is shown below. It starts from 1 and goes up to 10 for clarity in the examples.

Simple list of numbers from 1 – 10

Accessing a single value

To access a single value from the list you will use the following code:

myList[N]

where N is the position of the element we want within the list.

If you want to access the integer ’10’ from the list you may think you can use:

myList[10]

However, Python will throw an IndexError telling you ‘list index out of range’. The following diagram shows the actual index values in the top row.

myList with indices in the top row

The correct way to get the integer 10 is to use myList[9]:

myList[9]

REMEMBER Python uses ZERO indexing!

Accessing multiple values – Slicing

A list ‘slice’ is a contiguous serious of elements from the list. The code format is:

myList[Start : End + 1]

The slice uses a colon ‘:’ to separate the two indices. However, slicing has it’s own pitfall as you may have noticed from the above code. Suppose you want to select the integers 4 and 5 in myList. Remember the list is zero indexed so you are looking for index 3 and 4! You may think that:

myList[3:4] 

would do it it. However that would return 4!! A single value!

myList[3:4]

So what is happening here? There is a Start and End [3:4]. Why don’t we get 2 elements?

Think of it this way. End minus Start gives the number of elements you will get. Therefore 4 – 3 will give 1. That is why only a single element is returned. To return the integers 4 and 5 from the list, we need to use the code:

myList[3:5]

5 is the end and 3 is the start. Subtracting them gives 2 which is the number of elements that will be returned.

myList[3:5]

Another example. Say you want the slice 4,5,6,7. This is 4 elements. So Start will be 3 (remember zero indexing) and end will be index 3 + 4 which is index 7.

7 minus 3 gives 4 elements.

myList[3:7] returns [4,5,6,7]

Now the confusion begins!

You will see code like this:

myList[:4]
myList[-4:]
myList[::2]

At first these may look confusing. Where are the Start or End numbers? Why is there 2 ‘:’?

It is easier to think of the first 2 lines of code as HEAD and TAIL. If you want to return the first N elements of the list it will look like this:

myList[:N] returns the first N elements of the list

That is the HEAD of the list.

If you want to return the last 4 elements of the list it will look like this:

myList[-N:] returns the last N elements of the list

Last, but not least, we have 2 colons in our expression. In the example we have[::2]. The first colon is blank on both sides, meaning that the whole list is selected. The 2 after the second colon means that the list will be stepped through by 2 each time. This is better explained by a diagram:

myList[::N] The lis is stepped through in N steps

The step is 2 in the example. So the elements selected will be 0, 2, 2+2(4), 4+2(6) etc.

Conclusion

These examples cover the basics of slicing and indexing lists. Hopefully they help clear up the topic in your mind. It’s not so difficult after all!!

My advice is to keep lists simple. Don’t make lists of multiple data types if you can help it.

I hope this has been of some help and I look forward to comments and suggestions.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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