understand slice notation python

Understand Slice Notation in Python

In this tutorial you will understand slice notation works in Python, how to return a slice object and how to use slice object to specify how to slice a sequence.

Understand Slice Notation in Python

Understand Slice Notation in PythonThere are couple ways using which you can slice a given sequence. The most common way to slice a sequence is using “:” operator. In Python slicing allows you to obtain substring.

Syntax:

seq[ start: end: indexJump]

Whereas,

seq is the given sequence string or list, and in case of string the above syntax can be used to obtain substring i.e., portion of string starting from index “start” to end index “end” and index increment or jump size indexJump.

Note, the start is always included, end is always excluded. Therefore, seq[:i] + seq[i:] always results in seq.

For example,

Let’s say the given string is “python”.

>>> seq = "Python"

>>> seq[:2]+seq[2:]
'Python'

Similarly,

>>> seq[:4]+seq[4:]
'Python'

useful defaults for omitted index

Note, Python assigns useful defaults for omitted slice indices. For instance, the omitted start index defaults to zero and the omitted end index defaults to size of the given sequence (list or string).

Therefore, you get the following output when you omit both start and end indices.

>>> seq[:]
'Python'

Positive and negative indexes and slicing notation

As per Python documentation, you need to think that indices (both positive and negative indexes) are pointing between characters as depicted in the following diagram.

understand slice notation python

 

Note, the first row in the above diagram indicates positive indexes position numbers from o to 6 for the string. And second row indicates the corresponding negative indexes. When you slice the string from index i to index j, it will consists of all the characters between i and j.

For example,

>>> seq[2:4]
'th'

>>> seq[1:4]
'yth'

Similarly, let’s try negative indexes. Check the following examples negative indexes slicing.

>>> seq[-4:-2]
'th'

>>> seq[-5:-2]
'yth'

Note, when you attempt to use an index value that is too large you will get the following error:

>>> seq[40]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

However, when you use out of range indexes while slicing, it will be handled gracefully and you wont get any IndexError as shown below.

>>> seq[4:40]
'on'
>>> seq[40:]
''
>>> seq[40:40]
''

That’s it. Now you should have better understanding on slice notation in Python.

Hope it is helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments