1
>>> 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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
pylearner
  • 537
  • 2
  • 8
  • 26
  • 1
    The slice is well-defined but empty. The attempt to access an element that doesn't exist is undefined hence an error. – John Coleman Sep 29 '18 at 15:30

1 Answers1

2

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.

L3viathan
  • 26,748
  • 2
  • 58
  • 81