Python lesson 23
Slicing. Taking a Piece
Grab part of a list or part of a word, without touching the rest.
Start, Stop, Step
A slice uses square brackets with a colon: [start:stop]. It begins at start and stops just before stop. Leave a side empty to mean "all the way". A negative number counts backwards from the end.
scores = [10, 20, 30, 40, 50]
scores[0:3] # [10, 20, 30]. stops BEFORE 3
scores[:2] # [10, 20]. from the start
scores[3:] # [40, 50]. to the end
scores[-1] # 50. the last one
scores = [10, 20, 30, 40, 50]
print(scores[0:3])
print(scores[-1])
Where Does It Stop?
letters = ["a", "b", "c", "d", "e"]
print(letters[1:4])
Top Three Only
Slicing Words Too
Strings slice exactly like lists. Run it.
name = "Python"
print(name[0])
print(name[0:3])
print(name[-2:])
print(name[::-1])
Initials
Take the first letter of each name to build a set of initials.
first = "Ada"
last = "Lovelace"
initials = first[0] + "." + last[0] + "."
print(initials)
Is It a Palindrome?
A palindrome reads the same backwards. Slice with a step of -1 to reverse a word and compare.
word = "racecar"
backwards = word[::-1]
print(backwards)
print(word == backwards)
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.