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]

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github