Slicing in Python with Python Slice Function and Indexing

Hey there! As we are making headway through our Python journey, it’s time to learn a very useful concept in Python. It’s Slicing in Python. We’ll learn what slicing means and the different ways in which we can create slices. We’ll also learn to apply slicing on strings, tuples, and lists through various examples ahead. So stick along till the end of this article.

Slicing in python

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is Slicing in Python?

Slicing, as its name suggests is the process of accessing a particular piece of a sequence. Slicing is a feature in Python that lets you access parts of sequences like strings, tuples, and lists. These parts that you get after slicing are known as slices. Also, slices are non-destructive. This means that accessing a slice doesn’t change the original value of the sequence. But you can modify mutable sequences like lists by assigning new values to its slice(s).

Slicing in Python can be done using 2 methods:

  1. Using indexing to create slices.
  2. Using the slice() function to create a slice object for slicing.

Before we learn how to work with these two python methods, we need to understand Python’s slice notation.

Understanding slice notation: start, stop and step

The slice notation is a pre-requisite when it comes to implementing slicing in Python.
Let’s see what start, stop and step mean.

  1. The start value is an integer which indicates the starting index value.
  2. The stop value indicates the index value to stop at. The element at this index is not included in the slice.
  3. The step value refers to the number of steps(indices) to jump while going from start to stop.

Both the slicing methods discussed above make use of the slice notation. Let’s see how!

Indexing to create Python slices

We are familiar with the square bracket notation used to access elements in a sequence through their indices. Let’s look at some examples while working at the shell:

>>> mystring = "techvidvan"
>>> mystring[0]
't'
>>> mystring[-1]
'n'
>>>

Python supports accessing values of a sequence using both positive and negative indexing. Positive index values count from left to right, whereas negative index values count from right to left. So, in our example, mystring[0] gives the element at index 0, i.e, the first element. And mystring[-1] gives the element at index -1, i.e, the last element.

This square bracket notation can be extended to access slices of a sequence.
This is done by putting the slice notation inside the square brackets. The start, stop and step values are separated from one another by the colon (:) character as:

mystring[start:stop:step]

These three values are optional when used together:

  1. When start value is missing, it has a default value 0.
  2. When stop value is missing, it takes the value of the length of the sequence. (This is the maximum value stop can have)
  3. When step is missing, it takes the default value of 1.

Follow along through the Python shell session and look at the examples:

>>> digits = [10, 20, 30, 40]
>>> digits[:]
[10, 20, 30, 40]
>>> digits[:3]
[10, 20, 30]
>>> digits[2:]
[30, 40]
>>> digits[::2]
[10, 30]
>>> digits[-1: -4 : -1]
[40, 30, 20]

Using Python slice() function to create slices

We can use the slice() function to create slices. The slice function takes in the values of start, stop and step as arguments and returns a slice object. This slice object can then be passed within the square brackets in place of start:stop:step to access the desired slice.

slice() accepts three parameters:

  1. When start is missing, it defaults to None.
  2. stop can’t be optional.
  3. When step is missing, it takes the default value of None.

The steps involved while creating slices using a slice object:

Step 1: Creating a slice object:

>>> slice_object = slice(1, 5, 2)
>>> print(slice_object)

Output: slice(1, 5, 2)

Step 2: Using the slice object to access a slice:

>>> l = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> l[slice_object]

Output: [2, 6]

Let’s look at some more examples in the Python shell.

>>> l = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> slice_object = slice(5)
>>> l[slice_object]
[0, 2, 4, 6, 8]
>>> slice_object = slice(3, 7)
>>> l[slice_object]
[6, 8, 10, 12]
>>> slice_object = slice(2, 8, 2)
>>> l[slice_object]
[4, 8, 12]
>>> l[slice(-1,-7,-2)]
[18, 14, 10]

We saw how we can slice list. Now we’ll look at examples for slicing tuples and strings. Make sure to follow along at your >>> prompt, and experiment with slicing.

Slicing in python Tuples

Tuples work very similar to lists when it comes to slicing. The only difference is that you can use slicing to modify slices of a list but you cannot modify tuples as they are immutable.

  • Using indexing
    >>> digits = (10, 20, 30, 40)
    >>> digits[:]
    (10, 20, 30, 40)
    >>> digits[:3]
    (10, 20, 30)
    >>> digits[2:]
    (30, 40)
    >>> digits[::2]
    (10, 30)
    >>> digits[-1: -4 : -1]
    (40, 30, 20)
  • Using slice() function
    >>> digits = (10, 20, 30, 40)
    >>> digits[:]
    (10, 20, 30, 40)
    >>> digits[:3]
    (10, 20, 30)
    >>> digits[2:]
    (30, 40)
    >>> digits[::2]
    (10, 30)
    >>> digits[-1: -4 : -1]
    (40, 30, 20)

Slicing strings

A string is just a sequence of characters. We can use slicing to access parts of a string. We cannot modify slices of a string as strings are immutable.

  • Using Indexing
>>> greet = "Hello, world"
>>> greet[:]
'Hello, world'
>>> greet[::-1]
'dlrow ,olleH'
>>> greet[2:6]
'llo,'
>>> greet[::2]
'Hlo ol'
>>> greet[2:11:2]
'lo ol'
  • Using slice() function
>>> slice_obj = slice(6)
>>> greet[slice_obj]
'Hello,'
>>> greet[slice(3,10)]
'lo, wor'
>>> greet[slice(2,11,2)]
'lo ol'
>>> greet[slice(-1, -13, -1)]
'dlrow ,olleH'

Wrapping Up!

In this article, we learned the feature of slicing and how handy and powerful it is. We also looked at the methods through which we can access slices of a sequence. We advise you to take some time and understand how these examples work by using them in your code.

Hope you enjoyed reading this Python tutorial. Do share your feedback in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.