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.
s = "PYTHON" s[1:4] # "YTH" s[-2:] # "ON" s[::-1] # "NOHTYP"
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")
items = [1, 2, 3] n = 0 print(items[-n:])
reverse_string("hello") → "olleh"
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
Return every other item, starting with the first.
every_other([1, 2, 3, 4, 5]) → [1, 3, 5]
Return the last n items.
last_n([1, 2, 3, 4, 5], 2) → [4, 5]. Careful: last_n([1, 2, 3], 0) → [].
Split a list into chunks of size.
chunk([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]