Operators in Tuple


☞ We can use following operators on a Tuple.

 
1. Concatenation(+) Operator 
2. Replication(*) Operator
3. Membership(in,not in) Operator :
4. Comparison(<, >, <=, >=, ==, !=) Operator

Concatenation(+) Operator : Concatenation can be done only on tuple + tuple

Example 1 :
T1 = (10, 20, 30) + (40, 50, 60)
print(T1)

T2 = (40, 80) + (100,)
print(T2)
Output
 
(10, 20, 30, 40, 50, 60)
(40, 80, 100)
Example 2 :
 
T1 = (10, 20) + (3)
print(T1)
Output
 
T1 = (10, 20) + (3)
TypeError: can only concatenate tuple (not "int") to tuple

Replication(*) Operator : Replication can be done only on tuple * int

Example 1 :
T1 = (10, 20) * 3
print(T1)
Output
 
(10, 20, 10, 20, 10, 20)
Example 2 :
 
T1 = (10, 20) * 24.5
print(T1)
Output
 
T1 = (10, 20) * 24.5
TypeError: can't multiply sequence by non-int of type 'float'

Membership(in,not in) Operator :

  • in : It returns True if an element exists in the given tuple; Otherwise returns False
  • not in : It returns True if an element does not exist in the given tuple; Otherwise returns False
Example :
T1 = 20 in (10, 20, 30, 40)
print(T1)

T2 = (20,) in (10, 20, 30, 40)
print(T2)

T3 = (20,) in (10, 20, 30, 40, (20,))
print(T3)

T4 = (20,30) in (10, 20, 30, 40, (20,30))
print(T4)

T5 = 20, 30, 50 in (10, 20, 30, 40)
print(T5)

T6 = 20, 30, 40 in (10, 20, 40)
print(T6)

T7 = 50 in (10, 20, 30, 40, (75,60,50,55))
print(T7)
Output
 
True
False
True
True
(20, 30, False)
(20, 30, True)
False

Comparison(<, >, <=, >=, ==, !=) Operator :

  • It starts by comparing the first element from each sequence.
  • If they are equal, it goes on to the next element, and so on, until it finds elements that differ.
  • Subsequent elements are not considered(even if they are really big).
  • int and float are considered as same.
Example :
T1 = (10,) < (10, 20, 30, 40)
print(T1)

T2 = (10,) <= (10, 20, 30, 40)
print(T2)

T3 = (10,) >= (10, 20, 30, 40, 5)
print(T3)

T4 = (50,) > (10, 20, 30, 40)
print(T4)

T5 = (30,) >= (10, 20, 30, 40)
print(T5)

T6 = (30,) <= (10, 20, 30, 40)
print(T6)

T7 = (10, 20, 40000) > (10, 20, 30, 40, 5)
print(T7)
Output
 
True
True
False
True
True
False
True