Slicing in Python (Simple Guide)
Slicing means taking a part of a string, list, or similar data type.
The basic format is:
sequence[start : stop : step]
1. Parts of Slicing
Part | What It Does | Default
--------|----------------------|---------
start | Where to begin |0
stop | Where to stop | End
step | How much to skip |1
Example:
text = "Python Programming"
print(text[0:6]) # "Python"
2. How It Works
A. Using Positive Index
text = "ABCDEFGH"
Index: 0 1 2 3 4 5 6 7
Char: A B C D E F G H
print(text[2:5]) # "CDE"
print(text[:4]) # "ABCD"
print(text[3:]) # "DEFGH"
B. Using Negative Index
Index: -8 -7 -6 -5 -4 -3 -2 -1
Char: A B C D E F G H
print(text[-5:-2]) # "DEF"
print(text[-3:]) # "FGH"
3. Step in Slicing
A. Step Forward
text = "12345678"
print(text[1:7:2]) # "246"
print(text[::3]) # "147"
B. Step Backward
print(text[6:2:-1]) # "7654"
print(text[::-1]) # "87654321"
4. Leaving Out Start or Stop
text = "Python"
print(text[:3]) # "Pyt"
print(text[3:]) # "hon"
print(text[::-1]) # "nohtyP"
5. Works on Lists Too
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
print(nums[::2]) # [10, 30, 50]
print(nums[::-1]) # [50, 40, 30, 20, 10]
6. Common Uses
First 3 characters -> text[:3]
Last 3 characters -> text[-3:]
Reverse string/list -> text[::-1]
Every 2nd item -> list[::2]
Remove edges -> text[1:-1]
7. Edge Cases
text = "ABC"
print(text[5:10]) # ""
print(text[3:1]) # ""
8. Practice
text = "Hello World"
print(text[2:5]) # "llo"
text = "Programming"
print(text[::2]) # "Pormig"
nums = [1, 2, 3, 4]
print(nums[::-1]) # [4, 3, 2, 1]
Final Notes
- Slicing does not change the original data
- Works with strings, lists, tuples, etc.
- Use [::-1] to reverse a sequence