Tuple: In Python, a tuple is similar to a list. The difference between the two is that the elements of the tuple cannot be changed once it is assigned whereas in a list, elements can be changed. It’s used for heterogeneous data types. Tuples that contain immutable elements can be used as a key for a dictionary. A tuple can contain number of items and they may be of different types (integer, float, list, strings etc.).
However, there are certain advantages of implementing a tuple over a list like:
- We generally use tuple for heterogeneous datatypes and list for homogeneous datatypes.
- Since tuple are immutable, iterating through tuple is faster than with list.
- Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
- If you have data that doesn’t change, implementing it as tuple will guarantee that it should be remains write-protected.
Example:
Tuple1 = (“hi”, [1, 3, 4], (8, 6, 7))
Print(tuple1)
# empty tuple
demo_tuple = ()
print(demo_tuple)
# Tuple having integers values
demo_tuple = (1, 2, 3,4,5)
print(demo_tuple)
# tuple with mixed datatypes
demo_tuple = (1, “Hi”, 4.4)
print(demo_tuple)
# nested tuple
demo_tuple = (“key”, [2, 4, 6], (1, 3, 5))
print(demo_tuple)
# tuple can be created without parentheses
my_tuple = 4, 7.6, “hi”
print(demo_tuple)
# tuple unpacking is also possible
a, b, c = demo_tuple
print(a)
print(b)
print(c)