Tuples
Tuple is also a sequence of values much like a list. The values stored in a tuple can be of any type, and they are indexed by integers.
Tuples are immutable but also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries.
t = (12,323, 'd', [1,23], False)
Here t
is a tuple with values of different data types as int
, str
, list
and bool
. Each value is separated by a comma.
Even if a tuple has a single element, we need to mention the comma,
t = (1,)
type(t)
It returns tuple
. But if you write the first line without a comma then what will type(t)
return
We can also create a tuple using the function tuple
. With no argument, it creates an empty tuple:
t = tuple()
print(t)
Enter the empty tuple that will be printed
What if we pass an argument which is a sequence like a list, string or a tuple itself?
t1 = tuple("1,2,3,4,5")
t2 = tuple([1,2,3,4,5])
t3 = tuple((1,2,3,4,5))
Each statement creates a tuple with elements of the sequence passed as the argument.
Enter the number of elements in,
t1
t2
t3
Loading comments...