Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python allow list[a:b] but not list[a] if a and b are out of index range?

I am but a humble coding grasshopper and have a simple question.

Let:

x = ['this','is','a','list']

How come:

x[100:101]

outputs an empty list like expected, yet:

x[100]

is an error? Ditto for strings, please and thank you.

like image 370
Danny B Avatar asked Jul 16 '19 18:07

Danny B


People also ask

What to do if index is out of range Python?

“List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly. In the above example, we have created a list named “list_fruits” with three values apple, banana, and orange.

Why is my list index out of range?

You may get the IndexError: list index out of range error for the following reasons: Trying to access an index that doesn't exist in a list. Using invalid indexes in your loops. Specifying a range that exceeds the indexes in a list when using the range() function.

What does IndexError list index out of range mean in Python?

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

What does index () do in Python?

The Python index() method helps you find the index position of an element or an item in a string of characters or a list of items. It spits out the lowest possible index of the specified element in the list. In case the specified item does not exist in the list, a ValueError is returned.


1 Answers

It is basically a design choice of Python, and there is not really something right or wrong with either an error for x[100:101] versus giving an empty list.

Note that x[slice(...)] will always return a container (with the same type of x), while x[int] will always access the element at the specified position.

like image 175
norok2 Avatar answered Oct 10 '22 01:10

norok2