fbpx

What Is Slice Notation In Python?[The Ultimate Guide]

Understanding Slice Notation in Python

Python is an open-source programming language, introduced by Guido van Rossum in the year 1991. Since its inception, it has been preferred by many developers and programmers because of its easy-to-use syntax. It traditionally has all the features of a procedural programming language.

And additionally, it offers features of object-oriented programming too. The availability of several libraries that help solve mathematics, statistics, data visualization, machine learning problems, etc. adds to its vivaciousness and makes it a widely accepted and most frequently used programming language all over the world.

However, in this article, we are going to discuss what is slicing in Python and the notation associated with it?

But before we start discussing the concept of slicing in python 3, we must have a basic understanding of indexing in python3 and the next paragraph; you will read everything you need to know about indexing in Python.

The Daily Show Reaction GIF by The Daily Show with Trevor Noah - Find & Share on GIPHY

Indexing in Python3:

The elements like Strings, List, Tuples, Dictionaries, etc., are stored in sequential objects in Python and can be accessed using indexes.  A python sequence starts with a 0 index i.e., the first element in the sequence can be accessed using index 0, the second element with index 1, and so on. 

Have a look at the following example:

Accessing elements inside a list using indexes

Let’s create a sequence of type lists so that we can access elements from it using indexes.

  • Accessing the first element stored at 0th index:

  • Further, accessing the third element stored at the 2nd index:

  • Also, accessing the fifth element stored at the 4th index:

Accessing elements inside a tuple using indexes

Now that we have seen how to access elements inside a list using indexes, we will also see how to access elements inside a tuple.

Let’s create a sequence of type tuple so that we can access elements from it using indexes.

  • Accessing the second element stored at 1st index:

  • Further, accessing the fourth element stored at the 3rd index:

Negative Indexing in Python3:

Python3 also offers us the freedom to use reverse indexing to access our element inside the sequential object. The last element inside the sequence can be accessed using index ‘-1’, second last using index ‘ -2’, and so on.

 Let’s understand using an example:

Accessing elements inside a string using reverse indexing/negative indexing

Let’s create a sequence of type string so that we can access elements from it using negative indexes.

  • Accessing the last element inside the string stored at -1st index:

  • Also, accessing the third element from the last in the string stored at -3rd index:

Accessing elements inside a list using reverse indexing/negative indexing

Let’s create a sequence of type lists so that we can access elements from it using negative indexes.

  • Accessing second last element inside the list stored at -2nd index:

  • Further, accessing fourth last element inside the list stored at -4th index:

Slice Notation in Python:

Now that we have a good grasp of concepts of indexing in Python, we can proceed with the concept of slice notation in Python.

Slicing in Python is used to return a sequence in Python. This sequence can be anything string, list, tuple, dictionary, etc.

 Slicing follows a general syntax: [ start : stop ] and a further advanced syntax is: [ start : stop : step ]

  1. Let’s discuss the basic syntax first and how it can be used:

Taking an analogy of mathematics, the syntax [ start : stop ] can be interpreted as [start, stop) wherein we include the “start” index and move up to “stop -1”, i.e., excluding the stop index. Let’s understand this using few examples:

  List Slicing in Python:

We can use the concept of slicing in Python3 to get a sublist out of a list and the process is known as list slicing. Let’s see a few examples to understand the process of list slicing in Python 3.

  • Creating a list and accessing the first four elements inside the list

The point to understand here is the first element inside the list is stored at the 0th index, and the fourth element will be stored at the 3rd index so we have given ‘start value as 0’ and ‘stop value as 4’(4 will be exclusive, so it will count up to 3)  

  • Further, creating a sublist and accessing the elements from the 2nd index to 4th index inside the list

We are giving the range as 2 to 5 because it starts from the 2nd index and counts up to the 4th index (index 5 is exclusive)

  • Creating a sublist and accessing all the elements from the list

When we don’t pass any value inside the brackets, it assumes the Start value as the 0th index and the Stop value as the last index (it automatically counts up to last)  

  • Creating a sublist to start from the second index and count up to the last index

  • Also, creating a sublist to start from the 0th index and count up to the 2nd index

  1. Let’s discuss now the advanced second syntax also:

In the syntax: [ start: stop: step ], we include an additional parameter ‘step’ that can be used to skip elements in the sequence. One thing to keep in mind is that the default step value is always 1 unless we specify it specifically, that’s the reason why we say that the second syntax is an extension of the first.

For example: if we write [ 1: 6: 2], this means we start with the first element in the sequence and go till the seventh item skipping every second item in between.

It will return us a sublist as [‘Shyam’, ‘Dhoni’, ‘Mohit’]

 Let’s have a better understanding by seeing some more examples:

  • Creating a list and accessing elements from index 1 to 4th with a step size of 2
  • Further, creating a sublist to start from  0th index to count up to 4th index with a step size of 3 

  • Creating a sublist to start from the 0th index to count up to the last index with a step size of 2

Reversing a sequence using slicing operation:

One more very popular example of slicing is to reverse a sequence; in the next code snippet, we will see how we can use the slicing operation to reverse a sequence list and strings.

  • Reversing a list of numbers using the concept of slicing

In the next example, we will use our understanding of list slicing to reverse a list of numbers.

As discussed before, when we do not pass any values in ‘start’ and ‘stop’, then it assumes it as from the 0th index up to the last index in the list. However, when we use a negative step value then it starts from behind the list so in this manner we get a reverse of our original list. 

  • Reversing a string using the concept of slicing

We can also reverse string inside Python using the concept of slicing in the same manner as we did in reversing a list. See the code snippet below:

Final Thoughts:

In this article, our main motive was to understand the slice notation in Python and for that, we first understood the concept of indexing in Python. We extended the idea of indexes that explains how slicing in Python works. That also introduces the syntax and rules associated with it. Similarly, we can continue to work with negative indexes and other sequences like strings, tuples, dictionaries, etc.

Test your understanding slice notation in Python, attempt these practice questions now:

Question 1. Choose the correct output of the following code.

State = [‘New Delhi’, ‘Assam’, ‘Goa’, ‘Jammu and Kashmir’, ‘Uttar Pradesh’, ‘Rajasthan’, ‘Gujarat’  ]

print ( State[ : : ] )

  1. [ ‘New Delhi’,  ‘Goa’, ‘Jammu and Kashmir’,  ‘Rajasthan’  ]
  1. [ ‘New Delhi’, ‘Assam’, ‘Goa’, ‘Jammu and Kashmir’, ‘Uttar Pradesh’, ‘Rajasthan’, ‘Gujarat’  ]
  1. [ ‘Assam’, ‘Goa’, ‘Jammu and Kashmir’, ‘Uttar Pradesh’, ‘Rajasthan’, ‘Gujarat’  ]
  1. [ ‘New Delhi’, ‘Assam’, ‘Goa’, ‘Jammu and Kashmir’, ‘Uttar Pradesh’  ]

Correct Answer:

[‘New Delhi’, ‘Assam’, ‘Goa’, ‘Jammu and Kashmir’, ‘Uttar Pradesh’, ‘Rajasthan’, ‘Gujarat’  ]

As discussed earlier, when we do not pass any values in ‘start’ it implicitly assumes the list to be starting from the 0th index, and ‘stop’ is treated as the last index. Also, as discussed when we do not pass any value in ‘Step’ it considers it as 1, so no elements will be skipped in between. Hence option 2. is our correct output.

Question 2. Choose the correct output of the following code.

Boys = [‘Ram’, ‘Andrew’, ‘Trump’, ‘Narendra’, ‘Amit’, ‘Samay’ ]

print ( Boys[ 0 : : 2 ] )

  1. [‘Ram’, ‘Andrew’, ‘Trump’, ‘Narendra’, ‘Amit’, ‘Samay’ ]
  1. [‘Ram’, ‘Andrew’, ‘Trump’, ‘Narendra’ ]
  1. [‘Ram’, ‘Trump’, ‘Amit’ ]
  1. [‘Andrew’, ‘Narendra’, ‘Samay’ ]

Correct Answer:

[‘Ram’, ‘Trump’, ‘Amit’ ]

Start value is filled with the index ‘0’ therefore, we will start our sublist from the 0th index and stop is not defined so go till the last index. Now, the step value is 2, so we will skip 1 element in between the elements. Hence option 3. is our correct output.

Question 3. Choose the correct output of the following code.

Capitals = (‘Surat’, ‘Lucknow’, ‘Bangalore’, ‘Panjim’, ‘Patna’, ‘Chandigarh’)

print ( Capitals[ : : -2 ] )

  1. ( ‘Surat’, ‘Bangalore’, ‘Patna’ )
  1. ( ‘Lucknow’, ‘Banglore’, ‘Patna’, ‘Chandigarh’ )
  1. ( ‘Chandigarh’, ‘Patna’, ‘Panjim’, ‘Bangalore’, ‘Lucknow’, ‘Surat’ )
  1. ( ‘Chandigarh’, ‘Panjim’, ‘Lucknow’ )

Correct Answer:

( ‘Chandigarh’, ‘Panjim’, ‘Lucknow’ )

As we are passing a negative index in the Step field, our sequence will move in the reverse direction and start from the last index and will skip every second element in between and go till the 0th index. Hence option 4. is our correct output.

Question 4. Choose the correct output of the following code.

Capitals = [‘Surat’, ‘Lucknow’, ‘Bangalore’, ‘Panjim’, ‘Patna’, ‘Chandigarh’]

print ( Capitals[ 1 : 4 ] )

  1. [‘Surat’, ‘Lucknow’, ‘Bangalore’, ‘Panjim’]
  1. [‘Lucknow’, ‘Bangalore’, ‘Panjim’, ‘Patna’]
  1. [‘Lucknow’, ‘Bangalore’, ‘Panjim’]
  1. [‘Surat’, ‘Lucknow’, ‘Bangalore’, ‘Panjim’, ‘Patna’]

Correct Answer:

[‘Lucknow’, ‘Bangalore’, ‘Panjim’]

We will start accessing the list from the 1st index and will go till the 3rd index (as the 4th index will be exclusive). Hence option 3. is our correct option.

Question 5. Choose the correct output of the following code.

Artists = [‘Akon’, ‘Arijit’, ‘AR Rahman’, ‘Lady Gaga’, ‘Bieber’, ‘Samay’]

print ( Artists[ -3 :  : -1 ] )

  1. [‘Akon’, ‘Arijit’, ‘AR Rahman’, ‘Lady Gaga’, ‘Bieber’, ‘Samay’]
  1. [‘Samay’, ‘Bieber’, ‘Lady Gaga’, ‘AR Rahman’, ‘Arijit’, ‘Akon’]
  1. [ ‘Lady Gaga’, ‘AR Rahman’, ‘Arijit’, ‘Akon’]
  1. [‘Samay’, ‘Lady Gaga’, ‘Arijit’]

Correct Answer:

[ ‘Lady Gaga’, ‘AR Rahman’, ‘Arijit’, ‘Akon’]

We are providing a negative index in the step field. Therefore, we will start processing the list in reverse order and start from the -3rd index which is ‘Lady Gaga’ and go till the end of the list i.e., till ‘Akon’. Hence option 3. is our correct option.

Archana

Leave a Reply

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

Back to top