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.
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.
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.
I think it was a design decision with Python. When selecting a range, Python will return everything it can even if the list indices are out of range. But if selecting a single key or index, Python will give an error if the key doesn’t exist.
I guess the logic is that if you are selecting a range, you probably don’t care as much about the items than if you were select each item individually
calling x[100:101]
or x[100]calls the
getitem` function. according to the docs, this function should take in an integer or a slice object
https://docs.python.org/3/reference/datamodel.html#object.getitem
When you call x[100]
you are trying to look up the non-existent 100th item, raising an error. There is no 100th object.
When you call x[100:101]
you are passing in a slice object. this is handled differently. You get a slice of the list. In this case you get back []
because there are no items in that range.
Its still confusing.
Python slicing uses right-open intervals.
This has nice properties like the slices [a:b]
and [b:c]
not overlapping. Also the length of the slice [a:b]
is easy to calculate and verify: it is simply b - a
, not b - a + 1
, and an empty slice looks like [3:3]
, not [3:2]
. [0:5]
and [5:10]
cuts a ten element list nicely in half.
One way to think of it is to imagine a ruler, where the indices being points between the elements:
|e0|e1|e2|
0 1 2 3
The index of an element is the number to the left (closer to zero).
The slice [0:2]
goes from the |
mark above zero, to the |
mark above 2
, spanning e1
and e2
.
We can think of that 2
as referencing the right edge of element [1]
rather than denoting the index of the excluded element [2]
.