Slices with a step
You know slices from strings: text[a:b] is the part from index a up to, but not including, index b. Lists can be sliced in just the same way, and a slice of a list is a new list:
word = "keyboard"
print(word[3:6])
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[:2])
print(numbers[-2:])
print(numbers)
boa
[20, 30, 40]
[10, 20]
[50, 60]
[10, 20, 30, 40, 50, 60]Leaving out the first index starts from the beginning, and leaving out the second goes to the end, so numbers[-2:] is the last two items. The original list doesn't change: the slice is a copy of part of it.
A slice never stops the program with an IndexError. If it reaches past the end, it simply has fewer items: numbers[4:100] is [50, 60].
The step
Like range, a slice can have a third number, the step. [a:b:2] takes every second item:
letters = "abcdefgh"
print(letters[0:8:2])
print(letters[1::2])
print(letters[::3])
aceg
bdfh
adgletters[1::2] starts from index 1 and goes to the end, taking every second character. letters[::3] leaves out both ends and takes every third character of the whole string.
Going backwards
With a negative step, the slice goes from right to left. The start is then the greater index. Leaving out both ends with the step -1 gives the whole string or list in reverse:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[4:1:-1])
print(numbers[::-1])
word = input("Word: ")
print(word[::-1])
drawer[50, 40, 30]
[60, 50, 40, 30, 20, 10]
Word: drawer
reward[::-1] is the shortest way to reverse a string in Python.
Joining lists
Like strings, two lists can be joined with +. The result is a new list with the items of both, in order:
first = [1, 2, 3]
second = [7, 8]
print(first + second)
print(first[::-1] + second)
[1, 2, 3, 7, 8]
[3, 2, 1, 7, 8]