What is Tuple in Python?
A tuple is one of the four built-in collection data types in python, from the list, set, dictionary, and tuple.
As this is a collection data type, therefore tuple is used to store multiple items in a single variable.
A tuple is ordered meaning the items in the tuple are arranged in a way that we cannot change.
A tuple is indexed meaning each item in the tuple has its index value, so the first item in the tuple is at 0th index second item in the tuple is 1st index, and so on.
A tuple is immutable meaning once we declared a tuple we cannot add or remove an item into that tuple.
Tuple allows duplicate, since each item has its index value therefore, we can insert duplicate values inside a tuple.
How to use Tuple?
We define tuple in round brackets and give our tuple items inside those round brackets with comma-separated values. Also, we can give different data type values.
We can also define tuple using tuple constructor by using tuple built-in method.
Note: – We have passed our tuple items inside round brackets and then the whole square bracket is passed to tuple build in constructor tuple().
Also, we have printed data type on line number 3.
Methods of Tuple or Tuple methods.
Since Tuple is an immutable type of object the number of methods associated with tuple reduces significantly and we are left with only two built-in methods.
count( ) :- Returns a number of times a specified value is present inside tuple.
index( ): – It takes the value as an argument and returns the index value of that element. If there are duplicate values it will return the first index value.
- A tuple is one of 4 built-in collection data types
- Defined using round brackets ()
- Tuple() constructor is used
- Only 2 methods that is, count() & index()
FAQs or Interview questions for tuple?
Can we sort the tuple items?
Yes, we can sort the tuple items with the help of the sorted() method.
Can we find min and max of tuple item?
Yes, we can find the minimum and maximum tuple items with the help of the min(), max() function.
Is there any tuple comprehension on tuple or can we apply tuple comprehension?
Tuple does not support comprehension because we cannot add elements iteratively to tuple as it is an immutable collection data type.
What is tuple packing?
Read this article to understand fully about tuple packing.
Can I pass a single item, value to a tuple?
Yes, you can. Just pass the value inside round brackets and after that value specify comma (, )
Example: – variable = (22,)