Computer Science, asked by Nylucy, 8 months ago

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

Answers

Answered by poojan
5

An index out of bounds given with a list name causes an error, but not with list slices because

Slicing returns a list, and a list can be an empty one. While accessing through an index returns a value, that can't be 'None' as 'None' can be a string value too. So, it raises an error.

Example:

a=['a', 1, 'None', 7, 9]

print(a[5])    

Output: Index out of range Error

-> Accessing through the index. Raises 'Index out of range Error' as the indices present are 0, 1, 2, 3, 4.

print(a[5:8])

Output: []

Returns an empty list as there is no such indices set.

Learn more:

1. What is list comprehension python?

brainly.in/question/6964716

2. What is linked list in data structure?

https://brainly.in/question/6964440

Answered by ANSH7761
4

Slicing is used to create a new list. If the indices don't fall within the range of the number of elements in the list, we can return an empty list. So, we don't have to throw an error.

But, if we try to access the elements in the list which is greater than the number of elements, we cannot return any default value (not even None because it could be a valid value in the list). That is why

IndexError: list index out of range

is thrown.

While slicing, if the starting index is greater than or equal to the length of the sequence, the length of the returned sequence is set to be 0, in this line

defstop = *step < 0 ? -1 : length;

...

if (r->stop == Py_None) {

*stop = defstop;

}

...

if ((*step < 0 && *stop >= *start)

|| (*step > 0 && *start >= *stop)) {

*slicelength = 0;

For the Strings, if the length of the string to be returned after slicing is 0, then it returns an empty string, in this line

if (slicelength <= 0) {

return PyString_FromStringAndSize("", 0);

}

Similar questions