Indexes and Slices
Learn how to work with indexes and slices in Python.
We'll cover the following...
In Python, as in other languages, some data structures or types support accessing its elements by index. Another thing it has in common with most programming languages is that the first element is placed in the index number 0. However, unlike those languages, when we want to access the elements in a different order than usual, Python provides extra features.
For example, how do we access the last element of an array in C? If we think about it the same way we would in C, we would get the element in the position of the length of the array minus one. This would work in Python too, but we could also use a negative index number, which will start counting from the last element, as shown in the following commands:
my_numbers = (4, 5, 3, 9)print(my_numbers[-1])print(my_numbers[-3])
This is the preferred (Pythonic) way of doing things.
In addition to getting just one element, we can obtain many by using slice
, as shown in the following commands:
my_numbers = (1, 1, 2, 3, 5, 8, 13, 21)print(my_numbers[2:5])
In this case, the syntax on the square brackets means that we get all of the elements on the tuple, starting from the index of the first number (inclusive), up to the index on the second one (not including it). Slices work this way in Python by excluding the end of the selected interval.
We can exclude either one of the intervals, start or stop, and in that case, it will act from the beginning or end of the sequence, respectively, as shown in the ...