Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does str[64:] work while str[64] doesn't? [duplicate]

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

like image 582
pylearner Avatar asked Apr 14 '26 19:04

pylearner


1 Answers

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.

like image 121
L3viathan Avatar answered Apr 17 '26 07:04

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!