Python lists are used to store a collection of items. A single python list can store many different data types. You can also apply different types of functions to Python lists. For example, you can count the number of items in a list, you can add or subtract all the integers in a list of integers, you can insert, remove, and even sort list items. Today we’re going to explore how to apply list slicing to Python lists.

Python list slicing refers to the process of extracting subsets of a Python list by slicing the original list. Python lists can be of two types: One-dimensional lists and multidimensional lists. We’re going to show you how to apply slicing to both of these list types.

The best way to get comfortable with Python list slicing is by running a lot of examples. That’s precisely what we intend to do with this tutorial.

Slicing One-dimensional Python lists

A one dimensional list is a list in the form of a row. Here’s an example of a one-dimensional list:

my_list = ["A","B","C","D","E","F","G","H","I","J"]

Lists in Python follow zero-based indexing which means that the first item is stored at the 0th index while the last item is stored at N-1 index where N is the total number of items in a list. In the example above, A would be accessed with my_list[0] and J would be accessed with my_list[9].

To apply list slicing to a one-dimensional list, the following syntax is used.

sliced_list = list[start_index: end_index+1: step]

As shown in the above syntax, to slice a Python list, you have to append square brackets in front of the list name. Inside square brackets you have to specify the index of the item where you want to start slicing your list and the index + 1 for the item where you want to end slicing. The step parameter is optional and defines the number of items to skip while slicing the list. A step of 2 will skip 1 item and will return alternating items.

Slicing in the middle of a list

Let’s take a look at an example. In the following script we create a list of 10 items. The items are the first 10 letters of the English alphabet. Again, the first letter A is located at 0th index while the last letter J is located at the 9th index.

my_list = ["A","B","C","D","E","F","G","H","I","J"]

To slice the above list from letters C to G, follow this process. Since C is located at the 2nd index, we pass 2 as the start index and since G is located at the 6th index, we pass 6 + 1 = 7 as the end index.

my_slice = my_list[2:7]
print(my_slice)

Output:

['C', 'D', 'E', 'F', 'G']

Let’s now slice a list from C to G but with a step of 2.

my_slice = my_list[2:7:2]
print(my_slice)

Studying the output below, you’ll notice 1 item is skipped between each letter and only alternating items C to G are returned.

Output:

['C', 'E', 'G']

A step of 3 will skip two items and will return every third item.

Slicing the beginning of a list

If you want to return the items from the first (the 0th) to Nth index, do not pass any value for the start index and only pass the value for the end index. The following script returns all the values from the start of your list to the 6th index.

my_slice = my_list[:7]
print(my_slice)

Output:

['A', 'B', 'C', 'D', 'E', 'F', 'G']

Slicing the end of a list

In the same way, to slice a list starting from a specific index to the end of your list, only pass the start index and leave the end index empty. For example, the following script returns all the list items starting from the 2nd index till the end of list.

my_slice = my_list[2:]
print(my_slice)

Output:

['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

Slicing your list relative to the last item

You can also pass negative indices to slice a list. In negative indexing, the last index is considered as -1. In the following script the starting index is set to -7 while the end index is set to -2.

my_slice = my_list[-7:-2]
print(my_slice)

The letter at the -7th index of the list is D, while the letter just before the -2 index is H. Just like with positive indexing, the list slicing stops at the index just before the number you put in your slice. In this instance, H is the -3 index, so in the output of the code above, you’ll see a list of items from D to H:

Output:

['D', 'E', 'F', 'G', 'H']

You can also you use negative index to slice a list from the beginning or end.

For example, to slice a list from the beginning up to but not including the -2 index, use the following code.

my_slice = my_list[:-2]
print(my_slice)

Output:

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

Similarly, to slice a list starting from index number -7 to the end of the list, the following script can be used.

my_slice = my_list[-7:]
print(my_slice)

Output:

['D', 'E', 'F', 'G', 'H', 'I', 'J']
Can't get enough Python?

Enter your email address for more free Python tutorials and tips.

Python is powerful! Show me more free Python tips

Slicing Multidimensional Python lists

Just like one-dimensional lists, you can apply list slicing to multidimensional lists. A multidimensional list is simply a list of lists or nested lists. Here’s an example of a multidimensional list with 2 dimensions (i.e. columns and rows):

my_list2 = [["A", "B", "C", "D"],
           ["E", "F", "G", "H"],
           ["I", "J", "K", "L"],
           ["M", "N", "O", "P"]]

To apply list slicing to a two-dimensional list, the following syntax is used.

sliced_list = list[start_index_row, end_index_row + 1, step : start_index_column, end_index_column + 1, step]

Suppose you want to extract the items from the 2nd and 3rd rows and from 1st and 2nd columns of the my_list2 list we created earlier. To do so, you’d naturally try using the following list slicing syntax.

my_slice2 = my_list2[1:3, 0:2]
print(my_slice2)

However, executing the above script results in the following error.

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-30-23a529ae20a2> in <module>
      1 #my_slice2 = [start_index_row, end_index_row + 1 , start_index_column, end_index_row + ]
      2
----> 3 my_slice2 = my_list2[1:3, 0:2]
      4 print(my_slice2)

TypeError: list indices must be integers or slices, not tuple

The error says that the list indices cant be integers. To resolve this error, you have to convert your Python lists to numpy arrays. If you don’t already have NumPy installed, use the pip installer from your command line to install it:

pip install numpy

Once installed, you can use the following syntax to convert your list to a NumPy array.

import numpy
my_list2 = numpy.array(my_list2)

Now you can apply list slicing to the newly created numpy array that contains our two-dimensional data. The following script returns items from the 2nd and 3rd row and 1st and 2nd columns.

my_slice2 = my_list2[1:3, 0:2]
print(my_slice2)

Output:

[['E' 'F']
 ['I' 'J']]

Just like with one-dimensional lists, you can also select items from all rows or all columns of a multi-dimensional NumPy array. Let’s demonstrate this by executing the following script, which selects all the items from the first two rows of our multi-dimensional array.

my_slice2 = my_list2[:2, :]
print(my_slice2)

Output:

[['A' 'B' 'C' 'D']
 ['E' 'F' 'G' 'H']]

Again, like one-dimensional arrays, you can specify the slicing steps on multidimensional arrays, as well. For example, the following script selects items from alternate rows and all columns by using a step of 2.

my_slice2 = my_list2[::2, :]
print(my_slice2)

The output shows that rows 2 and 4 (with indices 1 and 3) are skipped.

Output:

[['A' 'B' 'C' 'D']
 ['I' 'J' 'K' 'L']]

Let’s see another example of slicing. The following script returns the 3rd and 4th column (2nd and 3rd index) of each row in our multi-dimensional list.

my_slice2 = my_list2[:, 2:]
print(my_slice2)

Output:

[['C' 'D']
 ['G' 'H']
 ['K' 'L']
 ['O' 'P']]

You can also skip alternating columns by passing a value for the step parameter. For example, the following script returns items from all the rows but only shows alternating columns (columns 1 and 3 with indices 0 and 2).

my_slice2 = my_list2[:, ::2]
print(my_slice2)

Output:

[['A' 'C']
 ['E' 'G']
 ['I' 'K']
 ['M' 'O']]

There’s no restriction prohibiting you from skipping both rows and columns in the same slicing statement. The following script alternates both the rows and columns by passing a step value for each dimension:

my_slice2 = my_list2[::2, ::2]
print(my_slice2)

In the output, you should see the items from the first and 3rd rows and first and 3rd columns.

Output:

[['A' 'C']
 ['I' 'K']]

Finally, you can use negative indexing with multidimensional lists, as well. For example, the following example returns the items from the last three rows and last three columns of our my_list2 list. To end this tutorial, we’re going to show you the complete code, with the NumPy declaration and all, to make sure we’re leaving you on sure footing

import numpy
my_list2 = [["A", "B", "C", "D"],
           ["E", "F", "G", "H"],
           ["I", "J", "K", "L"],
           ["M", "N", "O", "P"]]
my_list2 = numpy.array(my_list2)
my_slice2 = my_list2[-3:,-3:]
print(my_slice2)

Output:

[['F' 'G' 'H']
 ['J' 'K' 'L']
 ['N' 'O' 'P']]

Hopefully you’re a bit more confident with Python list slicing by now. We covered a lot of ground in this tutorial and presented over a dozen list slicing examples. If you found them helpful and want more Python guidance like this, join us using the form below:

Can't get enough Python?

Enter your email address for more free Python tutorials and tips.

Python is powerful! Show me more free Python tips