⬅ Previous Topic
Python DictionariesNext Topic ⮕
Python Sets⬅ Previous Topic
Python DictionariesNext Topic ⮕
Python SetsIn 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.
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 ()
.
fruits = ("apple", "banana", "cherry")
print(fruits)
('apple', 'banana', 'cherry')
Here, we created a tuple called fruits
that holds three items. The round brackets mean it's a tuple.
(x, y)
.fruits = ("apple", "banana", "cherry")
print(fruits[0])
apple
[0]
means we’re asking for the first item in the tuple.
print(len(fruits))
3
This tells us the tuple has 3 items.
for fruit in fruits:
print(fruit)
apple
banana
cherry
This goes through each item and prints it one by one.
print("banana" in fruits)
True
This checks if "banana" is inside the tuple.
Because tuples are unchangeable:
fruits[0] = "orange"
TypeError: 'tuple' object does not support item assignment
Python will give you an error if you try to change the content.
Since tuples can't be changed directly, here’s what you can do:
colors = ("red", "green", "blue")
print(colors[1]) # green
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)
('red', 'yellow', 'blue')
You cannot delete a specific item, but you can delete the whole tuple:
del colors
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.
⬅ Previous Topic
Python DictionariesNext Topic ⮕
Python SetsYou 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.