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 List of Lists with Examples
- Fix: ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none) ERROR: No matching distribution found for tkinter
- How to Convert Python Notebook .ipynb (JSON) to Executable .py Module
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python: Pandas Merge Indicator (Left, Right and Both) Example
- Fix: EOFError Exception in Python
- How to URL Decode a Query String in Python
- How to take user input from the console in a Python program
- Compare two lists in Python and return matches
- How to change the Python Default version
- Fix: KeyError: exception in Python
- How to get the Execution Time of A Python Program
- Fix: ModuleNotFoundError: No module named boto3 [Python]
- How to get unique values from a list in Python
- How to pip install Python Modules in VSCode
- Python: Fix - TypeError: NoneType object is not iterable
- How to delete a file using Python code example
- How to create a dictionary comprehension in Python
- Python: Get just the filename without extension using Path
- How to comment out a block of code in Python
- How to add two float numbers in Python
- Python: How to POST Json Data with HTTP Request
- Get MD5 Hash as Checksum of a String in Python
- Python - Convert float to String
- How to Parse XML String in Python
More Posts:
- Get the total size and number of objects of a AWS S3 bucket and folders - AWS
- When to use of() and ofNullable() methods of Optional in Java? - Java
- This operation couldnt be completed. Unable to locate a Java Runtime. [macOS] - MacOS
- Windows 10 now has a new enhanced Calculator with a new icon - News
- Change Google Chrome Browsers default download location - Chrome
- How to Know Which Python Version Installed on Jupyter Notebook - Python
- Fix: Unable to edit text in TextEdit on Mac - MacOS
- [fix] App store not working on Mac, Blank Black or White Screen - MacOS