Tuple Data Structure
In this article, we will discuss about Python tuple data structure. More specifically, what are tuples, how to create them, when to use them and various methods you should be familiar with.
Tuple is exactly same as List data structure except that it is immutable. i.e., once we creates Tuple object, we cannot perform any changes in that object. Hence Tuple is read only version of List.
If our data is fixed and never changes then we should go for Tuple.
In tuple data structure, insertion order is preserved and duplicates are allowed. Heterogeneous objects are allowed in tuple data structure.
We can preserve insertion order and we can differentiate duplicate objects by using index. Hence index will play very important role in Tuple also.
Tuple support both +ve and -ve index. +ve index means forward direction (from left to right) and -ve index means backward direction (from right to left).
We can represent Tuple elements within Parenthesis and with comma separator. Parenthesis are optional but recommended to use.
t=10,20,30,40,50 print(t) print(type(t))
Output
(10, 20, 30, 40, 50) <class 'tuple'>
Note
We have to take special care about single valued tuple.compulsory the value should ends with comma, otherwise it is not treated as tuple.
t=(10) print(t) print(type(t))
Output
10 <class 'tuple'>
E.g
t=(10,) print(t) print(type(t))
Output
(10,) <class 'tuple'>
Tuple Creation
1. t = ()
Creation of Empty Tuple
2. t = (10,)
t = 10,
Creation of Single valued Tuple, Parenthesis are Optional, should ends with Comma.
3. t = 10, 20, 30
t = (10, 20, 30)
Creation of multi values Tuples & Parenthesis are Optional.
4. By using tuple() Function
list=[10,20,30] t=tuple(list) print(t) t=tuple(range(10,20,2)) print(t)
Accessing Elements of Tuple
We can access either by index or by slice operator
1. By using Index
t = (10, 20, 30, 40, 50, 60) print(t[0]) ==> 10 print(t[-1]) ==> 60 print(t[100]) ==> IndexError: tuple index out of range
2. By using Slice Operator
t=(10,20,30,40,50,60) print(t[2:5]) ==> (30, 40, 50) print(t[2:100]) ==> (30, 40, 50, 60) print(t[::2]) ==> (10, 30, 50)
Tuple vs Immutability
- Once we creates tuple, we cannot change its content.
- Hence tuple objects are immutable.
E.g
t = (10, 20, 30, 40) t[1] = 70 ==> TypeError: 'tuple' object does not support item assignment
Mathematical Operators for Tuple
We can apply + and * operators for tuple.
1. Concatenation Operator (+)
t1=(10,20,30) t2=(40,50,60) t3=t1+t2 print(t3) ==> (10,20,30,40,50,60)
2. Multiplication Operator OR Repetition Operator (*)
t1=(10,20,30) t2=t1*3 print(t2) ==> (10,20,30,10,20,30,10,20,30)