list
string
tuple
It allows you to access multiple elements using a range of indexes.
sequence[start:stop:step]
Part | Meaning |
---|---|
start |
Index to begin slice (inclusive) |
stop |
Index to end slice (exclusive) |
step |
Interval between elements (default is 1) |
✅ If any of the parameters are omitted, defaults are:
start
= 0
stop
= length of sequence
step
= 1
my_list = [10, 20, 30, 40, 50, 60]
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[:3]) # Output: [10, 20, 30]
print(my_list[3:]) # Output: [40, 50, 60]
print(my_list[::2]) # Output: [10, 30, 50]
text = "Python"
print(text[0:3]) # Output: Pyt
print(text[::-1]) # Output: nohtyP (Reversed string)
t = (1, 2, 3, 4, 5)
print(t[::2]) # Output: (1, 3, 5)
Python supports negative indices, which count from the end:
my_list = [10, 20, 30, 40, 50]
print(my_list[-3:-1]) # Output: [30, 40]
print(my_list[::-1]) # Output: [50, 40, 30, 20, 10]
Use Case | Example Code | Result |
---|---|---|
First 3 elements | lst[:3] |
[10, 20, 30] |
Last 3 elements | lst[-3:] |
[40, 50, 60] |
Reverse list | lst[::-1] |
[60, 50, 40, 30, 20, 10] |
Every 2nd element | lst[::2] |
[10, 30, 50] |
nums = [0, 1, 2, 3, 4, 5, 6]
print(nums[1:6:2]) # Output: [1, 3, 5]
print(nums[::-2]) # Output: [6, 4, 2, 0]
No error is raised when start
or stop
go out of range.
lst = [1, 2, 3]
print(lst[1:10]) # Output: [2, 3]
print(lst[5:]) # Output: []
You can create a reusable slice object:
s = slice(1, 5, 2)
print([10, 20, 30, 40, 50, 60][s]) # Output: [20, 40]