Why substring slicing index out of range works in Python?



In many programming languages, trying to access the element that is out of range of a string or list results in the IndexError. But Python behaves differently when it comes to substring slicing.

Instead of generating the error, Python handles the out-of-range in slicing operations by adjusting the indices to fit the valid limits. This makes the Python slicing safe and appropriate. Let's dive into the article to understand how slicing with out-of-range indices works in Python with examples.

Python slice() Function

The Python slice() function is used to return the slice object that can be used for slicing sequences, such as lists, tuples.

Syntax

Following is the syntax for the Python slice() function -

slice(start, end, step)

Example 1

Let's look at the following example, where we are going to access the characters from index 1 to 19. Since the string has only 14 characters, it stops slicing at the end of the string.

str1 = "TutorialsPoint"
print(str1[1:20])

The output of the above program is as follows -

utorialsPoint

Example 2

Consider the following example, where we are going to access the characters from index 8 to 14, which are out of range, since the slicing beyond the string length does not throw an error, it returns an empty string.

str1 = "Welcome"
print("Result: ' " + str1[8:15] + "'")

The following is the output of the above program -

Result: ' '

Example 3

In the following example, we are starting at index 10 and trying to go up to index 30, but the string ends at index 25, so it returns from index 10 to the end.

str1 = "Welcome To TutorialsPoint"
print(str1[10:30])

The output of the above program is as follows -

TutorialsPoint

Example 4

Following is the example, where we are going to consider the negative index and perform slicing, since it is less than the start of the string, it adjusts it to 0 and slices from the beginning to index 2.

str1 = "Welcome"
print(str1[-9:3])

The output of the above program is as follows -

Wel
Updated on: 2025-06-10T19:14:50+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements