Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are list, set, and dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets ( ).
It is immutable.
The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. We can create a tuple by placing all the elements inside parentheses
(), separated by commas. It can have different types of elements.
tup = (1, 2, 3, 4, 5 )
Advantages of Tuple over List:
- We can generally use tuples for heterogeneous data types and lists for homogeneous data types.
- Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight performance boost.
- Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not possible.
- If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.