Tuples are just like Python lists except that they are immutable. You can not add, delete or change elements after creating a Tuple instance. Tuples is a built-in data type in Python to store data collections. A tuple is a collection of values separated by commas and enclosed in parentheses.
- Allow Duplicates: Tuples can contain duplicate values.
- Ordered: Tuple items have a defined order, and that order remains constant.
- Unchangeable: Once you create a tuple, you can’t add, remove, or modify its elements.
Remember, tuples are great for situations where you need an ordered, unchangeable collection of values.
Example
tpl = (1, 4, 5, True)
print (tpl [1]) # outputs 4
tpl [1] = 10 # throws an Exception of type TypeError
del tpl[1] # throws an Exception of type TypeError
Accessing Items
You can access tuple items using indexing (starting from 0):
tpl = ("Aaliyan", "Muhammad", "Ali")
print(tpl[0])
Outputs => Aaliyan
Length of a Tuple
Use the len() function to find the number of items in a tuple:
print(len(tpl))
Outputs => 3
Creating a Tuple with One Item
If you want a single-item tuple, include a comma after the item:
single_item_tuple = ("Aaliyan",)
Data Types in Tuples
Tuples can hold different data types.
mixed_tuple = ("abc", 34, True)
Type of a Tuple
Python defines tuples as objects with the data type “tuple“
print(type(mytuple))
Outputs => <class ‘tuple’>