Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I do Python Tuple Slicing?
Tuple slicing allows you to extract a portion of a tuple using the slice operator :. The syntax is tuple[start:stop:step], where start is the beginning index, stop is the ending index (exclusive), and step is optional.
Basic Tuple Slicing
The basic syntax uses start:stop to extract elements from index start to stop-1 ?
numbers = (10, 50, 20, 9, 40, 25, 60, 30, 1, 56)
# Extract elements from index 2 to 4 (exclusive)
slice1 = numbers[2:4]
print("numbers[2:4]:", slice1)
# Extract elements from index 1 to 6 (exclusive)
slice2 = numbers[1:6]
print("numbers[1:6]:", slice2)
numbers[2:4]: (20, 9) numbers[1:6]: (50, 20, 9, 40, 25)
Slicing with Missing Operands
When the start index is omitted, slicing begins from the beginning. When the stop index is omitted, slicing continues to the end ?
numbers = (10, 50, 20, 9, 40, 25, 60, 30, 1, 56)
# From index 6 to end
from_index = numbers[6:]
print("numbers[6:]:", from_index)
# From beginning to index 4 (exclusive)
to_index = numbers[:4]
print("numbers[:4]:", to_index)
# Entire tuple
entire = numbers[:]
print("numbers[:]:", entire)
numbers[6:]: (60, 30, 1, 56) numbers[:4]: (10, 50, 20, 9) numbers[:]: (10, 50, 20, 9, 40, 25, 60, 30, 1, 56)
Negative Indexing
You can use negative indices to slice from the end of the tuple ?
numbers = (10, 50, 20, 9, 40, 25, 60, 30, 1, 56)
# Last 3 elements
last_three = numbers[-3:]
print("numbers[-3:]:", last_three)
# All except last 2 elements
except_last_two = numbers[:-2]
print("numbers[:-2]:", except_last_two)
# From index -5 to -2 (exclusive)
middle_slice = numbers[-5:-2]
print("numbers[-5:-2]:", middle_slice)
numbers[-3:]: (30, 1, 56) numbers[:-2]: (10, 50, 20, 9, 40, 25, 60, 30) numbers[-5:-2]: (25, 60, 30)
Step Parameter
The optional step parameter allows you to skip elements during slicing ?
numbers = (10, 50, 20, 9, 40, 25, 60, 30, 1, 56)
# Every second element
every_second = numbers[::2]
print("numbers[::2]:", every_second)
# Every third element from index 1
every_third = numbers[1::3]
print("numbers[1::3]:", every_third)
# Reverse the tuple
reversed_tuple = numbers[::-1]
print("numbers[::-1]:", reversed_tuple)
numbers[::2]: (10, 20, 40, 60, 1) numbers[1::3]: (50, 40, 30) numbers[::-1]: (56, 1, 30, 60, 25, 40, 9, 20, 50, 10)
Conclusion
Tuple slicing uses the [start:stop:step] syntax to extract portions of a tuple. The result is always a new tuple, and you can use negative indices and step values for more flexible slicing operations.
