Python for Polyglots
Lesson 6 · Idioms

Slicing

seq[start:stop:step] works on lists, strings and tuples. start is included, stop is not, and every part is optional.

Negative numbers count from the end: -1 is the last item. A slice never raises an error for out-of-range values, but a single index like s[100] does. Slicing always returns a new object, so items[:] is a quick copy.

Taking a substring
s = "PYTHON"
s[1:4]     # "YTH"
s[-2:]     # "ON"
s[::-1]    # "NOHTYP"
Experiment
nums = list(range(10))
print(nums[2:5], nums[:3], nums[-3:], nums[::3], nums[::-1])

nums[1:3] = ["a", "b", "c"]   # assign to a slice: replace part of a list
print(nums)

s = "hello world"
print(s[:5].upper(), s[6:][::-1], s[100:], "<- empty, no error")
Quiz: What does this print?
items = [1, 2, 3]
n = 0
print(items[-n:])
Exercise 8: Reverse a string

reverse_string("hello") → "olleh"

Exercise 9: Palindrome

Return True if s reads the same backwards, ignoring case and anything that isn't a letter or digit.

is_palindrome("A man, a plan, a canal: Panama") → True

Exercise 10: Every other item

Return every other item, starting with the first.

every_other([1, 2, 3, 4, 5]) → [1, 3, 5]

Exercise 11: Last n items

Return the last n items.

last_n([1, 2, 3, 4, 5], 2) → [4, 5]. Careful: last_n([1, 2, 3], 0) → [].

Exercise 12: Chunk a list

Split a list into chunks of size.

chunk([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]