The concept of slicing in Python makes it very efficient to work with strings, lists, or tuples to extract a section from them with the help of range and indices.
Syntax:sequence[start:end:step]
Let's try to understand each of the parameters here,
Parameter | Description | Default Value |
---|---|---|
start | Starting index of the slice (inclusive) | 0 |
end | Ending index of the slice (exclusive) | Length of sequence |
step | Step size between elements in the slice | 1 |
Slicing with Strings Example:
Now let's start with a simple example of a string as a sequence.
sequence = "Let's try to learn sequences in Python!"
Slice | Result |
---|---|
'Let's' | Start: 0, End: 6, Step: 1 |
'sequences in Python!' | Start: 19, End: None, Step: 1 |
'to learn' | Start: 8, End: 16, Step: 1 |
'Let's try to learn sequences' | Start: 0, End: 23, Step: 1 |
'Python!' | Start: 25, End: None, Step: 1 |
'Let's in!' | Start: 0, End: 14, Step: 2 |
'!' | Start: -1, End: None, Step: 1 |
'Pytse ie' | Start: 26, End: 5, Step: -1 |
Once you get an understanding of how to slice what substring you are looking for, we can convert it into code.
Code:
sequence = "Let's try to learn sequences in Python!"
print(sequence[0:6]) # Result: "Let's"
print(sequence[19:]) # Result: "sequences in Python!"
print(sequence[8:16]) # Result: "to learn"
print(sequence[0:28]) # Result: "Let's try to learn sequences"
print(sequence[32:]) # Result: "Python!"
print(sequence[0:14:8]) # Result: "Ly"
print(sequence[-1:]) # Result: "!"
print(sequence[26:5:-1]) # Result: "ecneuqes nrael ot yrt"
Slicing with Lists Example:
Slice | Result |
---|---|
"Let's" | Start: 0, End: 6, Step: 1 |
"sequences in Python!" | Start: 19, End: None, Step: 1 |
"to learn" | Start: 8, End: 16, Step: 1 |
"Let's try to learn sequences" | Start: 0, End: 28, Step: 1 |
"Python!" | Start: 32, End: None, Step: 1 |
"Ly" | Start: 0, End: 14, Step: 8 |
"!" | Start: -1, End: None, Step: 1 |
"ecneuqes nrael ot yrt" | Start: 26, End: 5, Step: -1 |
Code:
list = [0.596, 0.105, 0.782, 0.421, 0.914, 0.290, 0.682, 0.813]
import random
decimal_numbers = [random.random() for _ in range(8)]
print(decimal_numbers) # Result: [0.596, 0.105, 0.782, 0.421, 0.914, 0.290, 0.682, 0.813]
print(decimal_numbers[0:]) # Result: [0.596, 0.105, 0.782, 0.421, 0.914, 0.290, 0.682, 0.813]
print(decimal_numbers[3:7]) # Result: [0.421, 0.914, 0.290, 0.682]
print(decimal_numbers[0:7:3]) # Result: [0.596, 0.782, 0.290]
print(decimal_numbers[-1::-1]) # Result: [0.813, 0.682, 0.290, 0.914, 0.421, 0.782, 0.105, 0.596]
print(decimal_numbers[-5:-1]) # Result: [0.105, 0.290, 0.682, 0.782]
print(decimal_numbers[3::2]) # Result: [0.421, 0.290, 0.105]
print(decimal_numbers[2:0:-1]) # Result: [0.682, 0.290, 0.421, 0.782]
print(decimal_numbers[4::-1]) # Result: [0.914, 0.421, 0.782, 0.105, 0.596]
Slicing with tuple Example:
cities = ('New York', 'Paris', 'London', 'Tokyo')
Slice | Result |
---|---|
('New York',) | Start: 0, End: 1, Step: 1 |
('Paris', 'London') | Start: 1, End: None, Step: 1 |
('Tokyo',) | Start: 2, End: 3, Step: 1 |
('New York', 'Paris', 'London', 'Tokyo') | Start: 0, End: None, Step: 1 |
('Tokyo', 'Paris') | Start: 2, End: None, Step: -1 |
() | Start: None, End: None, Step: None |
('London', 'Paris', 'New York') | Start: -1, End: None, Step: -1 |
('Paris', 'London') | Start: 1, End: 3, Step: 1 |
Code:
cities = ('New York', 'Paris', 'London', 'Tokyo')
print(cities[0:1]) # Result: ('New York',)
print(cities[1:]) # Result: ('Paris', 'London', 'Tokyo')
print(cities[2:3]) # Result: ('London',)
print(cities[0:]) # Result: ('New York', 'Paris', 'London', 'Tokyo')
print(cities[3:1:-1]) # Result: ('Tokyo', 'Paris')
print(cities[:]) # Result: ('New York', 'Paris', 'London', 'Tokyo')
print(cities[-1:]) # Result: ('Tokyo',)
print(cities[-2:-4:-1]) # Result: ('London', 'Paris')
Some more examples:
Slice | Result | Description |
---|---|---|
sequence[:] | Entire sequence | Returns a new sequence that is a copy of the entire sequence. |
sequence[::] | Entire sequence (equivalent to sequence[:]) | Returns a new sequence that is a copy of the entire sequence. |
sequence[::2] | Every second item | Returns a new sequence containing every second item. |
sequence[1::2] | Every second item starting at index 1 | Returns a new sequence containing every second item starting at index 1. |
sequence[::-1] | Reversed sequence | Returns a new sequence with items in reverse order. |
sequence[:5] | First five items | Returns a new sequence containing the first five items. |
sequence[-5:] | Last five items | Returns a new sequence containing the last five items. |
sequence[2:7] | Items from index 2 to 6 | Returns a new sequence containing items from index 2 to 6. |
sequence[1:-1] | Everything except the first and last items | Returns a new sequence excluding the first and last items. |
sequence[::3] | Every third item | Returns a new sequence containing every third item. |
sequence[:-2] | Everything except the last two items | Returns a new sequence excluding the last two items. |
sequence[-3:-1] | Second-last and third-last items | Returns a new sequence containing the second-last and third-last items. |
sequence[1:9:2] | Every second item from index 1 to 8 | Returns a new sequence containing every second item from index 1 to 8. |

-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Python,
- Python: Convert Date to DateTime
- How to sort a List using Lambda in Python
- Python matplotlib segmentation fault: 11 macOS Big Sur
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to install Python 3.11 on Mac
- How to flatten a nested list in Python
- Python: Pandas Merge DataFrames on Index Example
- How to Run all Cells at Once Jupyter Notebook
- Python - Convert float to String
- How to add borders to tkinter label text
- How to Exit a Loop in Python Code
- [Python] Fix: ValueError: All arrays must be of the same length
- Sorting an array using Bubble Sort in Python Programming
- How to Unzip a file using Python
- Python: Merge DataFrames Pandas Outer Join Example
- Change label (text) color in tkinter
- Convert Float to String in Python
- Fix: fatal error: No such file or directory compilation terminated
- Python: Access index/counter of a for loop iteration
- Import Other Python Files Examples
- How to install Anaconda on Mac (M1/M2 Mac)
- Python Regular Expression to Find All Matches in List
- How to Read a binary File with Python
- How to disable warnings while Python file execution
- Know current Python Version
More Posts:
- Your Android SDK is out of date or is missing templates. Please ensure you are using SDK version 22 or later. - Android
- Installing Visual Studio Code on Raspberry Pi - HowTos
- Android : No Launcher activity found! Error - Android
- How to Sort a LinkedList in Java - Java
- How to Install CVS Version Control on Linux/Ubuntu - Linux
- How to test Exceptions using Java JUnit - Java
- Android Studio Error:(19, 0) Gradle DSL method not found: android() - Android-Studio
- macOS Mail Fix: Authorization Error 400: invalid request - MacOS