The following list x has only a length of 3 and the max index would be 2, shouldn't it be throwing a index error instead of an empty list?
x = [1,2,3]
print(x[100:])
the output is
[]
CodePudding user response:
Unlike when indexing for a single element, indexing with a slice is allowed to go out of bounds. This is useful for slices like x[1:5]
where you don't need to know if there are at least 5 elements in x
. It will stop at the end of the actual data if it would go too far.
Here's an example where that comes in handy, a function that breaks up a list into chunks of up to some size n
:
def chunk(lst: list, n: int) -> list[list]:
result = []
for i in range(0, len(lst), n):
result.append(lst[i:i n])
return result
If you try running this a few times with input lists that are not exactly divisible by the chunk size, you'll see that the last element in the results will be shorter than the rest, even though we didn't code in a special case for the last chunk.
The forgiving nature of slices applies to both ends of a slice. As you've seen, if the indexes of the slice are entirely off the end of the list, you get an empty result instead of an error.
CodePudding user response:
It doesn't throw an error because you're using slice syntax. Since you sliced an out-of-bounds sequence Python returns the result of an empty list. I think the reasoning is that there are no values in that range of the list x
.
See note 4 from the documentation for Sequence Types — list, tuple, range:
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.