Python Data Structures
Python Slicing
Slicing lets you pull out a sub-section of a list, string, or tuple using the seq[start:stop:step] syntax, without writing a loop.
The start:stop:step Syntax
A slice takes up to three parts separated by colons: start (inclusive, default 0), stop (exclusive, default end of sequence), and step (default 1). Any part can be omitted.
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5]) # [2, 3, 4]
print(nums[:4]) # [0, 1, 2, 3]
print(nums[6:]) # [6, 7, 8, 9]
print(nums[::2]) # [0, 2, 4, 6, 8]Negative Indices
Negative numbers count from the end of the sequence, with -1 as the last item. They work in any part of the slice, which makes it easy to grab the last few items without knowing the length.
nums = [0, 1, 2, 3, 4, 5]
print(nums[-3:]) # [3, 4, 5] -> last 3 items
print(nums[:-2]) # [0, 1, 2, 3] -> all but the last 2Reversing a Sequence
A step of -1 walks backward through the sequence, making [::-1] the shortest way to reverse a list, string, or tuple without a loop.
text = "python"
print(text[::-1]) # 'nohtyp'
nums = [1, 2, 3, 4]
print(nums[::-1]) # [4, 3, 2, 1]Slicing Different Sequence Types
Slicing works the same way on any Python sequence type. A slice of a list returns a new list, a slice of a string returns a new string, and a slice of a tuple returns a new tuple.
| Sequence | Example | Result |
|---|---|---|
| List | [10, 20, 30, 40][1:3] | [20, 30] |
| String | "hello"[1:4] | 'ell' |
| Tuple | (1, 2, 3, 4)[:2] | (1, 2) |
Slicing never raises an IndexError even if start or stop is out of range — Python just clamps it to the sequence length.
