KnowledgeBoat Logo

Computer Science

An index out of bounds given with a list name causes error, but not with list slices. Why?

Python List Manipulation

24 Likes

Answer

When we use an index, we are accessing a constituent element of the list. If the index is out of bounds there is no element to return from the given index hence Python throws list index out of range error whereas list slicing always returns a subsequence and empty subsequence is a valid sequence. Thus, when a list is sliced outside the bounds, it still can return empty subsequence and hence Python gives no errors and returns empty subsequence.

Answered By

15 Likes


Related Questions