In Python, a tuple is an immutable data type. In Python, a tuple is a group of components surrounded in (). (parentheses). Once defined, a tuple cannot be amended; that is, neither its components nor its values can be changed.
Tuples in Python :
a=() # It’s an example of empty tuple
x=(1,) # Tuple with single value i.e. 1
tup1 = (1,2,3,4,5)
tup1 = (‘harry’, 5, ‘demo’, 5.8)
When generating tuples of a single element, it is necessary to use a comma (‘,’) after that element, like in the example below: tup=(1,) because the Python interpreter will treat it as a single entity if there is only one element inside the parenthesis.
Getting Values out of Tuples
Use the square brackets for slicing along with the index or indices to obtain the value located at that index to access values in tuples.
!/usr/bin/python
tup1 = (‘physics’, ‘chemistry’, 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print “tup1[0]: “, tup1[0];
print “tup2[1:5]: “, tup2[1:5];
When the above code is executed, it produces the following result −
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Tuple updates
Due to their immutability, tuples cannot be updated or have their element values changed. The example that follows explains how you can combine pieces of already-existing tuples to generate new tuples.
#!/usr/bin/python
tup1 = (12, 34.56);
tup2 = (‘abc’, ‘xyz’);
# Following action is not valid for tuples
# tup1[0] = 100;
# So let’s create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following result −
(12, 34.56, ‘abc’, ‘xyz’)
Removing tuple elements
Individual tuple elements cannot be eliminated. Naturally, there is nothing wrong with creating another tuple after eliminating the undesirable components. Use the del statement to specifically remove a whole tuple.
For example −
#!/usr/bin/python
tup = (‘physics’, ‘chemistry’, 1997, 2000);
print tup;
del tup;
print “After deleting tup : “;
print tup;
This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −
(‘physics’, ‘chemistry’, 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File “test.py”, line 9, in <module>
print tup;
NameError: name ‘tup’ is not defined