A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list or even a tuple.
- Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas.
- Like list and string, elements of a tuple can be accessed using index values, starting from 0.
- If there is only a single element in a tuple then the element should be followed by a comma. If we assign the value without a comma it is treated as integer.
- It should be noted that a sequence without parenthesis is treated as tuple by default.
Examples:
- tuple1 = (1,2,3,4,5)
- tuple2 = ('Mathematics',87,'Accountancy',78)
- tuple3 = (10,20,30,[40,50])
- tuple4 = (1,2,3,4,5,(10,20))
- tuple5 = 1,2,3
Accessing elements in a Tuple
Elements of a tuple can be accessed using indexing or slicing.
Examples:
Tuple is Immutable
Tuple is an immutable data type . It means that the elements of a tuple cannot be changed after it has been created. An attempt to do this would lead to an error. However an element of a tuple may be of mutable type.