In python, how are lists inclusive/exclusive when referencing the index? and why?
Or why do I need to use +1 to the index at the end of a selection in my list?
When selecting from a list in python, you may have noticed the saying ‘inclusive’ or ‘exclusive’, this is usually referring to the slice notation
mylist[start:stop] where the
start index is inclusive but the
stop index is exclusive. What does this mean?
If an index is inclusive, then that number will be included in the selection, while an exclusive will not be. Say, for example, we have the following list and two list slices.
list = [0, 1, 2, 3, 4, 5] list1 = list[:3] # [0, 1, 2] list2 = list[4:] # [4, 5]
As you can see, the
stop index of 3 is exclusive so the third index item (conveniently equal to 3) is not selected in
list1. On the other hand the 4 is included in
list2 since that number is inclusive.
Now lets say you want to select something based on the index number, since you know what that is. We want our new list to include start and stop so lets see:
start = 1 stop = 3 list3 = list[start:stop] # [1,2]
Unfortunately, this doesn’t include our desired stop since it is exclusive, so how can we include it? by shifting the index up 1.
list3 = list[start : stop + 1] #[1, 2, 3]
Finally, you may be asking why the developers would have made it this complicated? The best explanation comes from looking at half-open intervals:
list[:3] #the first 3 characters list[3:] #everything after the first 3 characters
I hope this all makes sense, please continue the discussion below and help each other out!