Operators in List


☞ We can use following operators on a List.

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

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

Example 1 :
L1 = [10, 20, 30] + [40, 50, 60]
print(L1)

L2 = [40, 80] + [100]
print(L2)
Output
 
[10, 20, 30, 40, 50, 60]
[40, 80, 100]
Example 2 :
 
L1 = [10, 20] + 3
print(L1)
Output
 
L1 = [10, 20] + 3
TypeError: can only concatenate list (not "int") to list

Note : If you will do list + datatype other than int, it will give you an error.


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

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

Note : If you will do list * datatype other than int, it will give you an error.


Membership(in,not in) Operator :

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

L2 = [20] in [10, 20, 30, 40]
print(L2)

L3 = [20] in [10, 20, 30, 40, [20]]
print(L3)

L4 = [20,30] in [10, 20, 30, 40, [20,30]]
print(L4)

L5 = 20, 30, 50 in [10, 20, 30, 40]
print(L5)

L6 = 20, 30, 40 in [10, 20, 40]
print(L6)

L7 = 50 in [10, 20, 30, 40, [75,60,50,55]]
print(L7)
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 :
L1 = [10] < [10, 20, 30, 40]
print(L1)

L2 = [10] <= [10, 20, 30, 40]
print(L2)

L3 = [10] >= [10, 20, 30, 40, 5]
print(L3)

L4 = [50] > [10, 20, 30, 40]
print(L4)

L5 = [30] >= [10, 20, 30, 40]
print(L5)

L6 = [30] <= [10, 20, 30, 40]
print(L6)

L7 = [10, 20, 40000] > [10, 20, 30, 40, 5]
print(L7)
Output
 
True
True
False
True
True
False
True