A slice specifies a sequence’s start, stop, and optional step bounds. Python uses the colon form inside square brackets to retrieve a subset, stopping before the final index. section 3.3 section 4.3
Use slices to control which sequence elements are selected:
- Write sequence[start:stop] for a contiguous range. section 4.3
- Add a third value—sequence[start:stop:step]—to skip elements. section 3.3
- Omit the start or stop to begin at the sequence’s first element or continue to its end. section 3.3 section 4.3
- Expect a slice to preserve the sequence type: lists produce lists, tuples produce tuples, and strings produce strings. section 4.3
- Rely on forgiving bounds when a slice extends beyond the sequence; Python truncates the result rather than raising an error. section 4.3
Select every other character
s = 'abcdefgh' print(s[2:6:2]) # ce print(s[::2]) # aceg Use mylist[-n:] with a for loop to process only the final n elements of a list. section 3.3 section 4.5
Use a slice as a loop range
def mysum(items): if not items: return 0 output = items[0] for item in items[1:]: output += item return output The items[1:] expression skips the base element and remains safe when only one item is supplied, because the resulting slice is empty. section 4.7
s = 'abcdefgh' print(s[2:6:2]) #1
Trace how a start, stop, and step select alternating elements from a string. section 3.3


