Tuples are immutable lists and cannot be changed in any way once it is created.
Some of the characteristics features of Tuples are:
- Tuples are defined in the same way as lists.
- They are enclosed within parenthesis and not within square braces.
- Elements of the tuple must have a defined order.
- Negative indices are counted from the end of the tuple, just like lists.
- Tuple also has the same structure where the values are separated by commas.
An example showing how to build tuples in Python:
tupl1 = ('computersc', 'IT', 'CSE'); tup2 = (6,5,4,3,2,1);
Accessing Values In Tuples
Programs to show how to access values in Tuples:
tupl1 = ('computersc', 'IT', 'CSE'); tupl2 = (1993, 2016); tupl3 = (2, 4, 6, 8, 10, 12, 14, 16); print ("tupl1", tupl1) print ("tupl3[2:4]", tupl3[2:4])
tupl1 computersc tupl3[2:4] (6, 8)
They are immutable, i.e., the values can't be changed directly. So we can just update by joining tuples. Let's demonstrate this with an example:
tupl1 = (2, 3, 4); tupl2 = ('ab', 'cd'); tupl3 = tupl1 + tupl2 print (tupl3)
This code snippet will execute a combination of two tuples using the "+" operator.
(2, 3, 4, 'ab', 'cd')
Delete Elements From Tuples
To delete a tuple, we can use the del-statement.
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16); del tupl3;