0
0
Pythonprogramming~5 mins

Tuple indexing and slicing in Python

Choose your learning style9 modes available
Introduction

Tuples store multiple items together. Indexing and slicing help you get specific items or parts from a tuple easily.

You want to get the first or last item from a list of fixed values.
You need to extract a part of a tuple, like a few elements in the middle.
You want to loop through only a section of a tuple.
You want to quickly check or use a single item from a tuple.
You want to reverse or skip items in a tuple.
Syntax
Python
tuple_name[index]
tuple_name[start:end]
tuple_name[start:end:step]

Indexing starts at 0 for the first item.

Slicing extracts items from start up to but not including end.

Examples
Gets the first item 'red' from the tuple.
Python
colors = ('red', 'green', 'blue')
print(colors[0])
Gets items from index 1 to 3: (20, 30, 40).
Python
numbers = (10, 20, 30, 40, 50)
print(numbers[1:4])
Negative index -1 gets the last item 'e'.
Python
letters = ('a', 'b', 'c', 'd', 'e')
print(letters[-1])
Gets every second item: (1, 3, 5).
Python
values = (1, 2, 3, 4, 5, 6)
print(values[::2])
Sample Program

This program shows how to get items from a tuple using indexing and slicing.

Python
fruits = ('apple', 'banana', 'cherry', 'date', 'fig')

# Get first fruit
first = fruits[0]

# Get last fruit
last = fruits[-1]

# Get middle fruits
middle = fruits[1:4]

# Get every other fruit
every_other = fruits[::2]

print(f"First fruit: {first}")
print(f"Last fruit: {last}")
print(f"Middle fruits: {middle}")
print(f"Every other fruit: {every_other}")
OutputSuccess
Important Notes

Trying to change a tuple item by index will cause an error because tuples cannot be changed.

Negative indexes count from the end: -1 is last, -2 is second last, and so on.

If you omit start in slicing, it starts from the beginning; if you omit end, it goes to the end.

Summary

Use indexing to get a single item from a tuple by position.

Use slicing to get a part of a tuple as a new tuple.

Negative indexes and steps help access items from the end or skip items.