Imagine that we have a variable with a list of Star Wars characters:
# Star Wars! star_wars = ["Luke", "Leia", "Han", "Vader", "Obi-Wan", "Chewie", "R2D2", "C3PO", "Emperor", "Jabba", "Lando"]
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?
# negative index print(star_wars[-1])
See example: 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.
Extract from a list
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:
# extract from the list extract = star_wars[2:5] print(extract)
['Han', 'Vader', 'Obi-Wan']
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 (see example):
ch1 = star_wars[4:] ch2 = star_wars[:6] print(ch1) print(ch2)
the following will happen:
- in the ch1 variable, there will be star_wars list elements displayed starting from the element with index 4 to the last element,
- the ch2 variable will contain star_wars list elements starting from the element with index 0 to the element with index 5 (remember that the end index does not fall into the range)
You can also use negative indexes in the ranges (see example):
ch3 = star_wars[-4:] print(ch3) Result: ['C3PO', 'Emperor', 'Jabba', 'Lando'] That is, from the fourth element from the end to the last element. ch4 = star_wars[1:-5] print(ch4)
['Leia', 'Han', 'Vader', 'Obi-Wan', 'Chewie']
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.
# We take every second element, starting with the first, # Up to and including the sixth. ch5 = star_wars[1:7:2] print(ch5) # ...and here we take every third one from start to end: ch6 = star_wars[::3] print(ch6) # Now we take every other element starting from the second from the end # up to the second from the beginning: ch7 = star_wars[-2:2:2] print(ch7) # ...and now the best: we reverse the order of the list: ch8 = star_wars[::-1] print(ch8)
See example: Extracting elements
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.
# Let's take the first character from the string txt = “A long time ago in a galaxy far, far away…” print(txt) Result: A ...and now we will extract the second word: word = txt[2:6] print(word) Result: long And now let's reverse the string: print(txt[::-1]) Result: ...yawa raf ,raf yxalag a ni oga emit gnol A