Let us have a variable with a list of Star Wars characters:
The star_wars variable stores a list of elements that are strings. In this lesson we will learn how to operate on lists in Python.
What happens if we give a negative index?
See example of a negative index
The program will display "Lando".
Index -1 simply means "take the first element from the end". Similarly, index -2 will return Jabba, -3 - Emperor, -4 - C3PO, and so on. Index -100 will throw an error, because the list doesn't have so many elements.
We can download a fragment of a list by entering two indices indicating the start and end of the desired fragment. Separate them by a colon, just like you see below:
See example of a fragment of the list
The result will be:
Something's wrong here, isn't it? Since the initial and final indexes are given in brackets, it should display characters from Han to Chewie, inclusive!
Well, no. In Python the final index is the one that is no longer in the range. Simply put, add 1 to the index of the last element you want to extract. So star_wars[2:5] will extract the elements of the star_wars list with indexes 2, 3, 4, but not the one with index 5!
If you omit the list index ...
... the following will happen:
You can also use negative indexes in the ranges.
Result:
That is, from the fourth element from the end to the last element.
See example of negative indexes
Result:
Note that the fifth element from the end is R2D2, but this element is out of range.
Python is designed so nicely that it even allows you to extract from the list not only a few , but for example every second, every third element - even counting from the end! You only need to add another parameter in square brackets (step), also separated with a colon.
See example of element extraction
Brilliant, isn't it?
But that's not all!
Let's go back to the beginning of the previous lesson, where we called the list a collection. A collection in computer science is an object that can store any number of other objects. So, in Python, a list is a collection. What else is a collection?
Yes! In Python a string is also a collection of single characters! And just as we can navigate a list, extract small fragments from it, reverse it - the same can be done with strings.
See example of text operations
Analyze the code. Here you will find a list of all The Beatles' albums, sorted from the oldest (index 0) to the newest. Display the band's first and last album.
Display the first five albums of the band on the screen.
Display on the screen all albums from third to seventh inclusive.
Now, display every second album, from the first to the last.
Finally, display all the albums from the oldest to the latest (use reversing of the array).
</div> </div>