Slicing of lists, syntax why?

hey there, I hope everyone is safe and alright.

I am doing the slicing lesson and came across the syntax which says we should end the slicing with an index larger than the last element’s index by one. I just want to know why is that and is the reason arbitrary or is it due to some limitation or something computational.

thanks!

I am uncertain of the exact reason why it works this way, but I believe it is because the computer will recognize that number as a sort of ‘stop’ code. Like saying:

“Continue working until 5:00, than you can stop.”

This statement obviously doesn’t mean keep working after 5:00, it means stop at 5:00.

lis = [1, 2, 3, 4, 5,]

sublist = lis[0:5]

The computer interprets this as keep working until you reach 5 than stop.

2 Likes

Oh that kinda makes sense, you mean like the null character in a string in c, right?

inclusive or exclusive. In this case they chose exclusive, which helps write code like this

x = lst[1:5]
y = lst[5:10]
z = lst[10:15]

instead of

x=lst[1:5]
y=lst[6:10]
z=lst[11:15]

It’s all about how they want the language to flow, basically preference - but it can have some profound impacts on how code is written

2 Likes

Oh I get it. Thanks a million!