0

Logic question

What is the login behind excluding the last element in output of a range or list in python? Like x[0:5] will exclude the last element, here 5th element.

14th Apr 2023, 4:47 AM
Rajiv K V
Rajiv K V - avatar
2 odpowiedzi
+ 7
Actually, x[0:5] excludes the 6th element and contains the 5th. Because indexing starts with 0. So this slice contains exactly 5 elements (with indices of 0 to 4). You'll just have to accept this is how it works. No reason to pry 'why', it was a choice made by the language designers. 😀 Maybe once you start using it in more code, you'll also find it convenient that it is implemented like this.
14th Apr 2023, 5:40 AM
Tibor Santa
Tibor Santa - avatar
+ 2
It makes it easier to concatenate slices, or create contiguous ones: something[:number] + something[number:] is exactly something. something[int * step:(int + 1) * step] yields perfectly contiguous slices. If it didn't exclude the last element, we'd have to subtract 1 for that.
15th Apr 2023, 3:55 PM
Emerson Prado
Emerson Prado - avatar