Part 04 / Topic 5 of 11
Slicing deep-dive
Slicing is seq[start:stop:step]. It cuts out a piece, like taking a few slices from a loaf of bread. It works on lists, tuples and strings. stop is not included. Any part can be left out.
Real-world example: a week of temperatures.
temps = [31, 33, 35, 34, 30, 29, 32] # Mon to Sun
print(temps[0:3]) # [31, 33, 35] first 3 days
print(temps[:3]) # [31, 33, 35] same thing
print(temps[4:]) # [30, 29, 32] from Friday to end
print(temps[-2:]) # [29, 32] last 2 days
print(temps[::2]) # [31, 35, 30, 32] every 2nd day
print(temps[::-1]) # [32, 29, 30, 34, 35, 33, 31] reversed
print(temps[5:1:-1]) # [29, 30, 34, 35] backwards from index 5 to 2
word = "MALAYALAM"
print(word == word[::-1]) # True (palindrome)
copy_of_temps = temps[:] # a slice makes a new (shallow) copy
| Slice | Meaning |
|---|---|
s[a:b] |
from a up to (not incl.) b |
s[:b] |
from start to b |
s[a:] |
from a to end |
s[::k] |
every k-th item |
s[::-1] |
reversed copy |
๐ Going deeper: slicing never raises
IndexError:temps[5:100]just gives what exists. Slicing a list always makes a new list. For astrortuple, CPython may give back the very same object for a full slice likeword[:](word[:] is wordโTrue). That is safe, because strings and tuples can never change. You can also assign to a slice of a list:temps[0:2] = [30, 30]replaces the first two items.
Done here? The practice set for Part 4 โ 8 exercises with solutions โ is on the part page.