>>> a = ["a", "b", "c", "d", "e", "f", "g", "h", "l"]
>>> a[30:]
[]
>>> a[:30]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'l']
I am trying to understand the logic behind this slicing. For example, when we try to reach element by indexing, it will give us an IndexError.
>>> a[12]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
We have got total 9 elements in the list. Yet, we can use any indexes which are greater than 8. Any technical explanations would be highly appreciated.
This makes sense if you see a slice like [i:j] as "make a list of all elements that have an index between i and j." If the original list has 3 elements, i is 5 and j is 7, then there are no elements that fulfill this requirement, so the result will be an empty list.
In practice, it turns out this property is useful quite often.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With