0
0
Pythonprogramming~5 mins

Why tuples are used in Python

Choose your learning style9 modes available
Introduction

Tuples are used to store a group of items together that should not change. They keep data safe and organized.

When you want to keep a list of values that should not be changed, like days of the week.
When you want to use a fixed set of values as keys in a dictionary.
When you want to return multiple values from a function safely.
When you want to group related data that belongs together and should stay the same.
Syntax
Python
tuple_name = (item1, item2, item3)
Tuples use parentheses ( ) and items are separated by commas.
Once created, you cannot change the items inside a tuple.
Examples
A tuple holding three color names.
Python
colors = ('red', 'green', 'blue')
A tuple representing a point with x and y coordinates.
Python
point = (10, 20)
An empty tuple with no items.
Python
empty = ()
A tuple with one item needs a comma after the item.
Python
single = ('hello',)
Sample Program

This program uses a tuple to return two values from a function: the minimum and maximum of a list. The tuple keeps these two results together and unchanged.

Python
def get_min_max(numbers):
    return (min(numbers), max(numbers))

values = [4, 7, 1, 9]
result = get_min_max(values)
print(f"Min: {result[0]}, Max: {result[1]}")
OutputSuccess
Important Notes

Tuples are faster than lists because they cannot change.

Use tuples when you want to protect data from accidental changes.

You can use tuples as keys in dictionaries, but lists cannot be used as keys.

Summary

Tuples store multiple items together that should not change.

They are useful for fixed collections of data.

Tuples help keep data safe and can be used as dictionary keys.