Navigating collections

Let us 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.

Negative indices

What happens if we give a negative index?

# negative index
print(star_wars[-1])

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.

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)

See example of a fragment of the list

The result will be:

['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!

Empty indexes

If you omit the list index ...

See live example

ch1 = star_wars[4:]
ch2 = star_wars[:6]
print(ch1)
print(ch2)

... the following will happen:

You can also use negative indexes in the ranges.

See live 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)

See example of negative indexes

Result:

['Leia', 'Han', 'Vader', 'Obi-Wan', 'Chewie']

Note that the fifth element from the end is R2D2, but this element is out of range.

Jumping

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 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?

Strings

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[0])
 
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

See example of text operations

Task 1

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.

Do the task See the solution

Task 2

Display the first five albums of the band on the screen.

Do the task See the solution

Task 3

Display on the screen all albums from third to seventh inclusive.

Do the task See the solution

Task 4

Now, display every second album, from the first to the last.

Do the task See the solution

Task 5

Finally, display all the albums from the oldest to the latest (use reversing of the array).

Do the task See the solution

Next chapter: Loops »

</div> </div>