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.
Structure of a Tuple
Tuples contain comma-separated values between round brackets/parentheses. The only difference from lists is that the square brackets [ ] in lists are replaced by parentheses ( ).
Introduction to Sequence Data Types
A sequence is an ordered collection of elements. It is called ordered because the elements will be maintained in a specific order and the order will not change. Consider the following example.
sample = 'computer'
print(sample)
my_list = list(sample)
print(my_list)
my_set = set(sample)
print(my_set)
prints, (LIST is categorized as an ordered data type and SET as an unordered data type)
computer ['c', 'o', 'm', 'p', 'u', 't', 'e', 'r'] {'r', 'p', 'm', 'c', 't', 'u', 'e', 'o'}
Creating a Tuple
sample = ('a', 'b', 44, 4.1)
print(type(sample))
sample2 = 'a', 'b', 44, 4.1 #no parenthesis
print(type(sample2))
print(sample, sample2) #both are same
prints,
<class 'tuple'> <class 'tuple'> ('a', 'b', 44, 4.1) ('a', 'b', 44, 4.1)
A tuple with a single element is a special case.
tuple_3 = ('a') #a string
print(type(tuple_3))
tuple_4 = ('a',) #equivalently tuple_4 = ‘a’,
print(type(tuple_4))
prints, (To create a tuple with a single element, a comma should be included after the element as shown above)