In Python, Tuple is similar to list However, unlike a list, they are immutable i.e they cannot be changed.
Also, a tuple is similar to a range with only one exception. In tuple, every element is included but in range, the last element is excluded.
Tuple is constructed with ( ) with elements separated by comma.
Let see with an example:-
#tuple tup=(0,1,2,5) print(tup) #printing with for loop for element in tup: print(element) #Legth of a Tuple print("Length: %d"%len(tup))
(0, 1, 2, 5) 0 1 2 5 Length: 4
One tuple can also store more than one type of objects.
#mix types tup = ('one', 1) print(tup)
Indexing and slicing in tuples are similar to that of strings in python.
tup=(0,1,2,5) #2nd from front print(tup) #3rd from back print(tup[-3])
Basic Tuple Methods
- count(x) – Count the how many ‘x’ is in the tuple.
- index(x) – Returns the index of ‘x’.
- min(tuple) – Returns minimum value item in the tuple.
- max(tuple) – Returns maximum value item in the tuple.
- len(tuple) – Length of the tuple.
- cmp(tuple_1,tuple_2) – Compares length of the tuple.
Why to use Tuple?
If in your program, you are passing objects and doesn’t want it to change and neither its sequence then tuple is the best option to do so.