Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

Python Tuples



In Python, a tuple is like a box where you can store a group of values — such as numbers or words — together. Once you put things into a tuple, you can't change them. That's what makes tuples special: they are fixed or unchangeable.

What Is a Tuple?

A tuple is a collection of items, just like a list, but it cannot be changed after it's created. Tuples are written using round brackets ().

Example:

fruits = ("apple", "banana", "cherry")
print(fruits)

Output:

('apple', 'banana', 'cherry')

Here, we created a tuple called fruits that holds three items. The round brackets mean it's a tuple.

Why Use Tuples?

Things You Can Do With Tuples

1. Access Items

fruits = ("apple", "banana", "cherry")
print(fruits[0])

Output:

apple

[0] means we’re asking for the first item in the tuple.

2. Check Length

print(len(fruits))

Output:

3

This tells us the tuple has 3 items.

3. Loop Through a Tuple

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

This goes through each item and prints it one by one.

4. Check If Item Exists

print("banana" in fruits)

Output:

True

This checks if "banana" is inside the tuple.

Things You Cannot Do With Tuples

Because tuples are unchangeable:

Trying to Change a Tuple (will cause an error)

fruits[0] = "orange"

Output:

TypeError: 'tuple' object does not support item assignment

Python will give you an error if you try to change the content.

Basic CRUD Operations with Tuples

Since tuples can't be changed directly, here’s what you can do:

Create

colors = ("red", "green", "blue")

Read

print(colors[1])  # green

Update

Tuples cannot be updated directly, but you can convert to a list, change it, and turn it back:

colors = ("red", "green", "blue")
color_list = list(colors)
color_list[1] = "yellow"
colors = tuple(color_list)
print(colors)

Output:

('red', 'yellow', 'blue')

Delete

You cannot delete a specific item, but you can delete the whole tuple:

del colors

Conclusion

Tuples are simple but powerful. Use them when you want to store a group of values that should never be changed. They are fast, memory-efficient, and great for keeping your data safe.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M