Tuple slicing in Python

Slicing means extracting a portion of a tuple using start:end:step.

Syntax

tuple[start:end:step]

Example: Slicing of Tuple

Python

# Tuple of numbers
numbers = (10, 20, 30, 40, 50, 60, 70)

# Slice from index 1 to 4 (end not included)
print("Slice (1:4):", numbers[1:4])      # using positive indexes

# Slice using negative indexes
print("Slice (-1:-4):", numbers[-1:-4])  # empty result
print("Slice (-4:-1):", numbers[-4:-1])  # valid slice
print("Slice (-4:0):", numbers[-4:0])    # empty result

Output Slice (1:4): (20, 30, 40)
Slice (-1:-4): ()
Slice (-4:-1): (40, 50, 60)
Slice (-4:0): ()

Note: When slicing, Python always moves from left to right. If the start index comes after the end index with a positive step, the result is an empty tuple.

Example: Slice from beginning or end

Python

# Tuple of numbers
numbers = (10, 20, 30, 40, 50, 60, 70)

# Slice from beginning to index 3
print("Slice (:3):", numbers[:3])

# Slice from index 3 to end
print("Slice (3:):", numbers[3:])

Output Slice (:3): (10, 20, 30)
Slice (3:): (40, 50, 60, 70)

Example: Slicing with step and reverse

Python

# Tuple of numbers
numbers = (10, 20, 30, 40, 50, 60, 70)

# Slice with step of 2
print("Slice (0:7:2):", numbers[0:7:2])

# Reverse tuple using slicing
print("Reversed tuple:", numbers[::-1])

Output Slice (0:7:2): (10, 30, 50, 70)
Reversed tuple: (70, 60, 50, 40, 30, 20, 10)