Python Arena
Step 1 of 5

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)
Output
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])
Output
aceg
bdfh
adg

letters[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])
Input
drawer
Output
[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)
Output
[1, 2, 3, 7, 8]
[3, 2, 1, 7, 8]

Your task

Challenge 1 of 3

Fill in the blank with a slice, so the program prints the word backwards and tells whether it's a palindrome, a word that reads the same both ways:

Word: level
level
A palindrome!

Challenge 2

A simple way to shuffle a deck of cards is to take every second card from the top into one pile, and put the rest after them. Write the function shuffle(cards: list) -> list, which returns a new list with the cards at indexes 0, 2, 4, ... first and then the cards at indexes 1, 3, 5, ... For example, shuffle([1, 2, 3, 4, 5]) returns [1, 3, 5, 2, 4].

Challenge 3

What does this program print? Type each line it prints.