How to Use Tuple Slicing in Python: Examples Included

How to Use Tuple Slicing in Python: Examples Included

Tuple slicing in Python lets you get a part of a tuple by setting a range of indices. The syntax is tuple[start:stop:step], where start is the first element to include, stop is the first element not to include, and step is the interval for picking elements. If you leave out any of these, they use default values.

Here are five examples illustrating tuple slicing in Python:

  1. Basic Tuple Slicing:
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Extract elements from index 2 to index 5 (exclusive)
result = my_tuple[2:6]
print(result)  # Output: (3, 4, 5, 6)
  1. Tuple Slicing with Negative Indices:
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Extract elements from the second last element to the end
result = my_tuple[-2:]
print(result)  # Output: (9, 10)
  1. Tuple Slicing with a Step Size:
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Extract every second element
result = my_tuple[::2]
print(result)  # Output: (1, 3, 5, 7, 9)
  1. Reverse a Tuple using Slicing:
my_tuple = (1, 2, 3, 4, 5)

# Reverse the tuple using slicing
result = my_tuple[::-1]
print(result)  # Output: (5, 4, 3, 2, 1)
  1. Slice with Custom Step Size:
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# Extract elements with a step size of 3
result = my_tuple[::3]
print(result)  # Output: (1, 4, 7, 10)

In each example, the tuple slicing operation creates a new tuple containing elements selected according to the specified range and step size. Tuple slicing is a powerful feature in Python for working with subsets of tuples efficiently.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!