Slicing

An index gets one item. A slice gets a part of a list. You write it as [start:end].

letters = ["a", "b", "c", "d", "e"]

print(letters[1:3])
print(letters[:2])
print(letters[-2:])
print(letters[::-1])
print(letters[3:99])
print("python"[1:4])

Output:

['b', 'c']
['a', 'b']
['d', 'e']
['e', 'd', 'c', 'b', 'a']
['d', 'e']
yth

The item at start is included, but the item at end is not. So letters[1:3] gives the items at index 1 and 2. If you leave out start, the slice begins at the start of the list. If you leave out end, it goes to the end of the list.

You can add a second colon and a step. A step of -1 moves backward through the list, so letters[::-1] gives a reversed copy. If end is past the last item, Python simply stops at the end of the list. That is why letters[3:99] works without an error. The last line shows that slicing works on strings too.

In the exercise, slice a list using positions from the input, then reverse it.