Understanding slicing in Python?

Better Stack Team
Updated on January 26, 2023

Slicing is a way of extracting a specific part of an array.

The syntax is following:

 
my_list[start:end]   # items start through end-1
my_list[start:]      # items start through the rest of the array
my_list[:end]        # items from the beginning through end-1
my_list[:]           # a copy of the whole array

You can also use a step argument with all of the above:

 
my_list[start:end:step]

Start represents the first value that is present in the new array and stop represents the first value that is not present. Step sets how many values we move over when taking the next element. The default is 1, meaning that we don’t skip any value from start to end - 1.

You can also use negative numbers. In that case, elements will be counted from end to start.

Here are some examples:

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

# second element from the end
print( my_list[-2] )         # 8

# two last elements
# note that if : is used the return type is array
print( my_list[-2:] )        # [8, 9]

# from the second element to the rest
print( my_list[2::1] )       # [3, 4, 5, 6, 7, 8, 9]

# from the start to the second element reversed (first three values)
print( my_list[2::-1] )      # [3, 2, 1]

# all except the last element reveresed
print( my_list[-2::-1] )     # [8, 7, 6, 5, 4, 3, 2, 1]
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack