When a program needs part of a string, list, or tuple, slicing retrieves a sub-sequence with compact index notation. The form sequence[start:stop:step] selects elements from start, stops before stop, and optionally advances by step. Omitting boundaries means starting at the beginning or continuing to the end. section 2.3 section 3.2
Use slicing to express common sequence operations directly:
- s[2:6] retrieves positions 2 through 5; s[2:6:2] takes every second element. section 2.3
- s[::2] selects every other element from the whole sequence. section 2.3
- items[1:] iterates over everything after the first element, making it useful when the first value is handled separately. section 3.7
- Slices tolerate bounds beyond the sequence, returning the available portion or an empty sequence; individual indexes instead raise an IndexError. section 3.2
- A slice preserves the sequence type: slicing a list returns a list, and slicing a tuple returns a tuple. section 3.2
Selecting and reusing sequence parts
s = 'abcdefgh'\nprint(s[2:6]) # 'cdef'\nprint(s[2:6:2]) # 'ce'\nprint(s[::2]) # 'aceg'\n\ndef firstlast(sequence):\n return sequence[0] + sequence[-1]\n\nt1 = ('a', 'b', 'c')\nprint(firstlast(t1)) # ('a', 'c') is not produced by this expression; the operation combines elements according to their types\n\nFor accumulation, assign items[0] as the initial value and loop over items[1:], avoiding an artificial starting value of zero. A one-element input makes items[1:] empty, so the loop simply runs zero times. section 2.3 section 3.2 section 3.7
s = 'abcdefgh' print(s[2:6]) #1
Run the compact string example to observe an ordinary range slice and its exclusive upper bound. section 2.3















