Last Updated : 09 Dec, 2024
Python tuples are immutable sequences used to store collections of heterogeneous data. They are similar to lists but cannot be changed once created. One of the powerful features of Python is slicing, which allows us to extract a portion of a sequence and this feature is applicable to tuples as well.
In this article, we will explore how to perform slicing on tuples, including the syntax, examples and practical uses.
What is Tuple Slicing?Tuple slicing is a technique to extract a sub-part of a tuple. It uses a range of indices to create a new tuple from the original tuple.
Basic Slicing ExamplesLet's consider a tuple and perform some basic slicing operations.
Python
# Define a tuple
tup = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# Slice from index 2 to 5
s1 = tup[2:6]
print(s1)
# Slice from the beginning to index 3
s2 = tup[:4]
print(s2)
# Slice from index 5 to the end
s3 = tup[5:]
print(s3)
# Slice the entire tuple
s4 = tup[:]
print(s4)
(2, 3, 4, 5) (0, 1, 2, 3) (5, 6, 7, 8, 9) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Let's explore tuple slicing in detail:
Syntax:The syntax for slicing is straightforward:
tuple[start:stop:step]
Negative indices can be used to slice tuples from the end.
Python
# Define a tuple
tup = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# Slice from the third last to the end
s1 = tup[-3:]
print(s1)
# Slice from the beginning to the third last
s2 = tup[:-3]
print(s2)
# Slice from the third last to the second last
s3 = tup[-3:-1]
print(s3)
(7, 8, 9) (0, 1, 2, 3, 4, 5, 6) (7, 8)Using Step in Slicing
The step parameter allows us to define the increment between indices for the slice.
Python
# Define a tuple
tup = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# Slice with a step of 2
s1 = tup[1:8:2]
print(s1)
# Slice with a negative step (reverse the tuple)
s2 = tup[::-1]
print(s2)
(1, 3, 5, 7) (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4