Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does substring slicing with index out of range work?

Why doesn't 'example'[999:9999] result in error? Since 'example'[9] does, what is the motivation behind it?

From this behavior I can assume that 'example'[3] is, essentially/internally, not the same as 'example'[3:4], even though both result in the same 'm' string.

like image 848
ijverig Avatar asked Feb 28 '12 21:02

ijverig


People also ask

What happen if you use out of range index with slicing?

The slicing operation doesn't raise an error if both your start and stop indices are larger than the sequence length. This is in contrast to simple indexing—if you index an element that is out of bounds, Python will throw an index out of bounds error. However, with slicing it simply returns an empty sequence.

Can we use slicing in range in python?

Slicing range() function in Python Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.

What does ::- 1 mean in slicing?

So [::-1] means from 1st element to last element in steps of 1 in reverse order. If you have [start:stop] it's the same as step=1 . So [:-1] it means all but last. again it's the last element exclusive.

How is slicing different from indexing?

“Indexing” means referring to an element of an iterable by its position within the iterable. “Slicing” means getting a subset of elements from an iterable based on their indices.


1 Answers

You're correct! 'example'[3:4] and 'example'[3] are fundamentally different, and slicing outside the bounds of a sequence (at least for built-ins) doesn't cause an error.

It might be surprising at first, but it makes sense when you think about it. Indexing returns a single item, but slicing returns a subsequence of items. So when you try to index a nonexistent value, there's nothing to return. But when you slice a sequence outside of bounds, you can still return an empty sequence.

Part of what's confusing here is that strings behave a little differently from lists. Look what happens when you do the same thing to a list:

>>> [0, 1, 2, 3, 4, 5][3] 3 >>> [0, 1, 2, 3, 4, 5][3:4] [3] 

Here the difference is obvious. In the case of strings, the results appear to be identical because in Python, there's no such thing as an individual character outside of a string. A single character is just a 1-character string.

(For the exact semantics of slicing outside the range of a sequence, see mgilson's answer.)

like image 184
senderle Avatar answered Sep 28 '22 15:09

senderle