What indexes do I use to access the elements I want?


#1

Question

What indexes do I use to access the elements I want?

Answer

There’s a simple key to using list slices, and that’s remembering this rule:
[inclusive : exclusive]
All that means is that the first index we write is included in the slice, and the second is excluded. Because of this, we start with the index we want, and end one index after the last index we want.
If I have my_list = [0, 1, 2, 3] and want the numbers 2 and 3, which are in indexes 2 and 3 respectively, I would start with the index I want, and end one index after the last one I want, like this:
my_slice = my_list[2:4]
Even though there is no 4th index in our list, it’s safe to write it like that because it stops before it gets to that index!


FAQ: Learn Python: Python Lists and Dictionaries - List Slicing