
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Why substring slicing index out of range works in Python?
Slicing outside the bounds of a sequence (at least for built-ins) doesn't cause an error. Indexing returns a single item, but slicing returns a subsequence of items. So when you try to index a nonexistent value, there's nothing to return; but when you slice a sequence outside of bounds, you can still return an empty sequence. For example:
>>> s = [1, 2, 3] >>> s[5:8] []
But if you just use an index out of bounds, it'll give you an error:
>>> s = [1, 2, 3] >>> s[5] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
- Related Articles
- Alternate range slicing in list (Python)
- Return the lowest index in the string where substring is found in a range using Python index()
- How to capture index out of range exception in C#?
- Return the highest index in the string where substring is found in a range using Python rindex()
- For each element return the lowest index in the string where substring is found in a range in Python
- For each element return the highest index in the string where substring is found in a range in Python
- Python program to sort strings by substring range
- Python – Extract elements in between multiple specific range of index
- Golang program to delete the ith index node, when index is the out of range in the linked list.
- Return the lowest index in the string where substring is found using Python index()
- What is slicing in Python?
- How to find index of last occurrence of a substring in a string in Python?
- How out-gridview selection works in PowerShell?
- Python List Comprehension and Slicing?
- Difference between indexing and slicing in Python

Advertisements