top

Search

Python Tutorial

The term operator refers to a symbol (or sometimes a phrase of alphabets) which is predefined to perform a certain process such as addition, comparison etc. Each symbol requires one or more objects for the process to be performed. The objects are called operands and symbol itself is called operator. Most of the operators are binary in nature, in the sense they require two operands. Unary operator requires only one operand.Arithmetic operatorsEverybody is familiar with arithmetic operators performing addition, subtraction, multiplication and division. Python has additionally modulus exponent and floor operators.OperatorPurposeDescription+AdditionAdds operands on either side of the operator.-SubtractionSubtracts right hand operand from operand on left.*Multiplicationreturns Multiplication of values on either side of the operator./Divisionleft operand acts as numerator and right operand denominator for division% Modulusreturns remainder of division of left hand operand by right.**ExponentCalculates value of operand raised to right.a**3 is a raised to 3 i.e. a*a*a//Floor DivisionThe division of operands where the result is the quotient in which the digits after the decimal point are removed. But division is negative, the result is floored, i.e., rounded away from zero (towards negative infinity).In [1]: a,b=21,10 #addition a+b Out[1]: 31 In [2]: #subtraction a-b Out[2]: 11 In [3]: #multiplication a*b Out[3]: 210 In [4]: #division a/b Out[4]: 2.1 In [5]: #modulus a%b Out[5]: 1 In [6]: #floor of positive division a//b Out[6]: 2 In [7]: #floor of negative division -a//b Out[7]: -3In-place assignment operatorsThese operators allow any arithmetic operation and assignment in one step. Result of corresponding arithmetic operation of two operands is assigned back to left operand.symbolpurposeDescription=assignmentAssigns values from right side operands to left side operand+=Add AND assignadds right operand to the left and assign result to left operand-=Subtract AND assignsubtracts right operand from left and assign the result to left operand*=Multiply AND assignmultiplies right operand with left and assign result to left operand/=Divide AND assigndivides left operand with right and assign result to left operand%=Modulus AND assignassigns modulus of two operands and assigns result to left operand**=Exponent AND assignPerforms exponentiation of left operand by right  and assign result to the left operand//=Floor Division and assignIt performs floor division on operators and assign value to the left operandIn [14]: a,b=21,10 #add and assign a+=b a Out[14]: 31 In [15]: a,b=21,10 #subtract and assign a-=b a Out[15]: 11 In [16]: a,b=21,10 #multiply and assign a*=b a Out[16]: 210 In [17]: a,b=21,10 #divide and assign a/=b a Out[17]: 2.1 In [18]: a,b=21,10 #modulus and assign a%=b a Out[18]: 1 In [19]: a,b=21,10 #exponent and assign a**=b a Out[19]: 16679880978201 In [20]: a,b=21,10 #floor and assign a//=b a Out[20]: 2Logical operatorsIn order to compare two objects for equality or to decide whether one is greater than other etc. the logical comparison operators are used. Primarily used with numeric objects, they can very well be used with other Python objects such as string, list or tuple.SymbolpurposeDescription==equalsreturns true if both operands are equal false otherwise!=not equal toreturns true if both operands are not equal false otherwise>greater thanreturns true if left operand is greater than right operand, otherwise false<less thanreturns true if left operand is less than right operand, otherwise false>=greater than or equal toreturns true if left operand is greater or equal to right operand, otherwise false<=less than or equal toreturns true if left operand is less than or equal to right operand, otherwise falseIn [8]: a=21 b=10 # equals a==b Out[8]: False In [9]: #not equal to a!=b Out[9]: True In [10]: #greater than a>b Out[10]: True In [11]: #less than a<b Out[11]: False In [12]: #greater than or equal a>=b Out[12]: True In [13]: #less than or equal to a<=b Out[13]: FalseSequence operatorsThis category of operators is common to all sequence data type i.e. string, list and tuple. All of them use zero based index to access items in them. Hence operators for indexing and slicing have been commonly defined.symbolpurposeDescription+ConcatenationAppends second sequence to first*Repetitionconcatenates multiple copies of the same sequence[]SliceGives the item at given index[ : ]Range Slicefetches item in range specified by two index operands separated by : symbol.If first operand is omitted, range starts at zero indexIf second operand is omitted, range goes upto end of sequenceinMembershipReturns true if a item exists in the given sequencenot inMembershipReturns true if a item does not exist in the given sequenceIn [21]: s1,s2="Hello","World" l1,l2=[1,2,3],[4,5,6] t1,t2=(1,2,3),(4,5,6) In [22]: #concatenation print (s1+s2) print (l1+l2) print (t1+t2) HelloWorld [1, 2, 3, 4, 5, 6] (1, 2, 3, 4, 5, 6) In [23]: #repetition print (s1*3) print (l1*3) print (t1*3) HelloHelloHello [1, 2, 3, 1, 2, 3, 1, 2, 3] (1, 2, 3, 1, 2, 3, 1, 2, 3) In [24]: #slice print(s2[2]) print (l2[2]) print (t2[2]) r 6 6 In [25]: s1='Hello World' l1=[1, 2, 3, 4, 5, 6] t1=(1, 2, 3, 4, 5, 6) In [26]: #range slice of string print (s1[2:5]) print (s1[:3]) print (s1[4:]) llo Hel o World In [27]: #range slice on list print (l1[2:4]) print (l1[:3]) print (l1[3:]) [3, 4] [1, 2, 3] [4, 5, 6] In [28]: #range slice on tuple print (t1[2:4]) print (t1[:3]) print (t1[3:]) (3, 4) (1, 2, 3) (4, 5, 6) In [29]: s1='Hello World' l1=[1, 2, 3, 4, 5, 6] t1=(1, 2, 3, 4, 5, 6) In [30]: 'He' in s1 Out[30]: True In [31]: 'W' not in s1 Out[31]: False In [32]: 10 in l1 Out[32]: False In [33]: 100 not in l1 Out[33]: True In [34]: 10/2 in t1 Out[34]: True In [35]: 10/3 not in t1 Out[35]: TrueSet operatorsThese operators are specifically designed for performing operations on set data type as defined in set theory of Mathematics.purposedescriptionUnionUnion of two sets is a set of all elements in both.IntersectionIntersection of two sets is a set containing elements common to bothDifferenceDifference of two sets results in a set containing elements only in first but not in second set.Symmetric differenceResult of Symmetric difference is a set consisting of elements in both sets excluding common elementIn [36]: set1,set2={10,20,30,40,50},{20,40,60} In [37]: #union set3=set1|set2 set3 Out[37]: {10, 20, 30, 40, 50, 60} In [38]: #intersection set3=set1&set2 set3 Out[38]: {20, 40} In [39]: #difference set3=set1-set2 set3 Out[39]: {10, 30, 50} In [40]: #symmetric difference set3=set1^set2 set3 Out[40]: {10, 30, 50, 60}Identity operatorsThese operators are not really symbols but phrases. Each Python object is allocated required space in computer memory. Address of memory location is obtained by built-in id() function. Python variable is really reference name given to this location. More than one variables can refer to same location. Following identity operators tell us if id() values of both objects is same or different.OperatorDescriptionisreturns true if both operands point to the same object and false otherwise.is notreturns true if both operands don’t point to the same object and false otherwise.In [41]: a=10 b=a print (id(a), id(b)) a is b 1860398432 1860398432 Out[41]: True In [42]: a=10 b=a*2 print (id(a), id(b)) a is b 1860398432 1860398752 Out[42]: FalseBitwise operatorsAny object in memory is represented in binary bits. The bitwise representation of object is manipulated by following operators. In following illustration, built-in bin() function is used to verify result of operations. The bin() function returns the binary equivalent of integer object. For example:a=45 and bin(45) is 00101101b=25 and bin(25) is 00011001Following table lists the bitwise operators.symbolOperatorDescription&Binary AND0&0=0 0&1=01&0=0 1&1=1|Binary OR 0|0=0 0|1=1 1|0=1 1|1=1^Binary XOR 0^0=0 0^1=1 1^0=1 1^1=0~Binary Ones ComplementIt is unary operator that flips bits.<<Binary Left Shiftbits moved to left by specified places and adds trailing 0s>>Binary Right Shiftbits moved to right by specified places and adds leading 0sIn [43]: a,b=45,25 bin(a),bin(b) Out[43]: ('0b101101', '0b11001') In [44]: #binary and c=a&b c, bin(c) Out[44]: (9, '0b1001') In [45]: #binary or c=a|b c, bin(c) Out[45]: (61, '0b111101') In [46]: #binary xor c=a^b c, bin(c) Out[46]: (52, '0b110100') In [47]: #binary complement c=~a c, bin(c) Out[47]: (-46, '-0b101110') In [48]: #left shift c=a<<2 c, bin(c) Out[48]: (180, '0b10110100') In [49]: #right shift c=a>>2 c, bin(c) Out[49]: (11, '0b1011')Just to verify bitwise & operation on a and b by using truth table for & operatora = 45 = 00101101 b = 25 = 00011001 ----------------------- a&b     = 00001001 = 9
logo

Python Tutorial

Python - Operators

The term operator refers to a symbol (or sometimes a phrase of alphabets) which is predefined to perform a certain process such as addition, comparison etc. Each symbol requires one or more objects for the process to be performed. The objects are called operands and symbol itself is called operator. Most of the operators are binary in nature, in the sense they require two operands. Unary operator requires only one operand.

Arithmetic operators

Everybody is familiar with arithmetic operators performing addition, subtraction, multiplication and division. Python has additionally modulus exponent and floor operators.

OperatorPurposeDescription
+AdditionAdds operands on either side of the operator.
-SubtractionSubtracts right hand operand from operand on left.
*Multiplicationreturns Multiplication of values on either side of the operator.
/Divisionleft operand acts as numerator and right operand denominator for division
Modulusreturns remainder of division of left hand operand by right.
**ExponentCalculates value of operand raised to right.
a**3 is a raised to 3 i.e. a*a*a
//Floor DivisionThe division of operands where the result is the quotient in which the digits after the decimal point are removed. But division is negative, the result is floored, i.e., rounded away from zero (towards negative infinity).
In [1]:
a,b=21,10
#addition
a+b
Out[1]:
31
In [2]:
#subtraction
a-b
Out[2]:
11
In [3]:
#multiplication
a*b
Out[3]:
210
In [4]:
#division
a/b
Out[4]:
2.1
In [5]:
#modulus
a%b
Out[5]:
1
In [6]:
#floor of positive division
a//b
Out[6]:
2
In [7]:
#floor of negative division
-a//b
Out[7]:
-3

In-place assignment operators

These operators allow any arithmetic operation and assignment in one step. Result of corresponding arithmetic operation of two operands is assigned back to left operand.

symbolpurposeDescription
=assignmentAssigns values from right side operands to left side operand
+=Add AND assignadds right operand to the left and assign result to left operand
-=Subtract AND assignsubtracts right operand from left and assign the result to left operand
*=Multiply AND assignmultiplies right operand with left and assign result to left operand
/=Divide AND assigndivides left operand with right and assign result to left operand
%=Modulus AND assignassigns modulus of two operands and assigns result to left operand
**=Exponent AND assignPerforms exponentiation of left operand by right  and assign result to the left operand
//=Floor Division and assignIt performs floor division on operators and assign value to the left operand
In [14]:
a,b=21,10
#add and assign
a+=b
a
Out[14]:
31
In [15]:
a,b=21,10
#subtract and assign
a-=b
a
Out[15]:
11
In [16]:
a,b=21,10
#multiply and assign
a*=b
a
Out[16]:
210
In [17]:
a,b=21,10
#divide and assign
a/=b
a
Out[17]:
2.1
In [18]:
a,b=21,10
#modulus and assign
a%=b
a
Out[18]:
1
In [19]:
a,b=21,10
#exponent and assign
a**=b
a
Out[19]:
16679880978201
In [20]:
a,b=21,10
#floor and assign
a//=b
a
Out[20]:
2

Logical operators

In order to compare two objects for equality or to decide whether one is greater than other etc. the logical comparison operators are used. Primarily used with numeric objects, they can very well be used with other Python objects such as string, list or tuple.

SymbolpurposeDescription
==equalsreturns true if both operands are equal false otherwise
!=not equal toreturns true if both operands are not equal false otherwise
>greater thanreturns true if left operand is greater than right operand, otherwise false
<less thanreturns true if left operand is less than right operand, otherwise false
>=greater than or equal toreturns true if left operand is greater or equal to right operand, otherwise false
<=less than or equal toreturns true if left operand is less than or equal to right operand, otherwise false
In [8]:
a=21
b=10
# equals
a==b
Out[8]:
False
In [9]:
#not equal to
a!=b
Out[9]:
True
In [10]:
#greater than
a>b
Out[10]:
True
In [11]:
#less than
a<b
Out[11]:
False
In [12]:
#greater than or equal
a>=b
Out[12]:
True
In [13]:
#less than or equal to
a<=b
Out[13]:
False

Sequence operators

This category of operators is common to all sequence data type i.e. string, list and tuple. All of them use zero based index to access items in them. Hence operators for indexing and slicing have been commonly defined.

symbolpurposeDescription
+ConcatenationAppends second sequence to first
*Repetitionconcatenates multiple copies of the same sequence
[]SliceGives the item at given index
[ : ]Range Slicefetches item in range specified by two index operands separated by : symbol.
If first operand is omitted, range starts at zero index
If second operand is omitted, range goes upto end of sequence
inMembershipReturns true if a item exists in the given sequence
not inMembershipReturns true if a item does not exist in the given sequence
In [21]:
s1,s2="Hello","World"
l1,l2=[1,2,3],[4,5,6]
t1,t2=(1,2,3),(4,5,6)
In [22]:
#concatenation
print (s1+s2)
print (l1+l2)
print (t1+t2)
HelloWorld
[1, 2, 3, 4, 5, 6]
(1, 2, 3, 4, 5, 6)
In [23]:
#repetition
print (s1*3)
print (l1*3)
print (t1*3)
HelloHelloHello
[1, 2, 3, 1, 2, 3, 1, 2, 3]
(1, 2, 3, 1, 2, 3, 1, 2, 3)
In [24]:
#slice
print(s2[2])
print (l2[2])
print (t2[2])
r
6
6
In [25]:
s1='Hello World'
l1=[1, 2, 3, 4, 5, 6]
t1=(1, 2, 3, 4, 5, 6)
In [26]:
#range slice of string
print (s1[2:5])
print (s1[:3])
print (s1[4:])
llo
Hel
o World
In [27]:
#range slice on list
print (l1[2:4])
print (l1[:3])
print (l1[3:])
[3, 4]
[1, 2, 3]
[4, 5, 6]
In [28]:
#range slice on tuple
print (t1[2:4])
print (t1[:3])
print (t1[3:])
(3, 4)
(1, 2, 3)
(4, 5, 6)
In [29]:
s1='Hello World'
l1=[1, 2, 3, 4, 5, 6]
t1=(1, 2, 3, 4, 5, 6)
In [30]:
'He' in s1
Out[30]:
True
In [31]:
'W' not in s1
Out[31]:
False
In [32]:
10 in l1
Out[32]:
False
In [33]:
100 not in l1
Out[33]:
True
In [34]:
10/2 in t1
Out[34]:
True
In [35]:
10/3 not in t1
Out[35]:
True

Set operators

These operators are specifically designed for performing operations on set data type as defined in set theory of Mathematics.

purposedescription
UnionUnion of two sets is a set of all elements in both.
IntersectionIntersection of two sets is a set containing elements common to both
DifferenceDifference of two sets results in a set containing elements only in first but not in second set.
Symmetric differenceResult of Symmetric difference is a set consisting of elements in both sets excluding common element
In [36]:
set1,set2={10,20,30,40,50},{20,40,60}
In [37]:
#union
set3=set1|set2
set3
Out[37]:
{10, 20, 30, 40, 50, 60}
In [38]:
#intersection
set3=set1&set2
set3
Out[38]:
{20, 40}
In [39]:
#difference
set3=set1-set2
set3
Out[39]:
{10, 30, 50}
In [40]:
#symmetric difference
set3=set1^set2
set3
Out[40]:
{10, 30, 50, 60}

Identity operators

These operators are not really symbols but phrases. Each Python object is allocated required space in computer memory. Address of memory location is obtained by built-in id() function. Python variable is really reference name given to this location. More than one variables can refer to same location. Following identity operators tell us if id() values of both objects is same or different.

OperatorDescription
isreturns true if both operands point to the same object and false otherwise.
is notreturns true if both operands don’t point to the same object and false otherwise.
In [41]:
a=10
b=a
print (id(a), id(b))
a is b
1860398432 1860398432
Out[41]:
True
In [42]:
a=10
b=a*2
print (id(a), id(b))
a is b
1860398432 1860398752
Out[42]:
False

Bitwise operators

Any object in memory is represented in binary bits. The bitwise representation of object is manipulated by following operators. In following illustration, built-in bin() function is used to verify result of operations. The bin() function returns the binary equivalent of integer object. For example:

a=45 and bin(45) is 00101101

b=25 and bin(25) is 00011001

Following table lists the bitwise operators.

symbolOperatorDescription
&Binary AND

0&0=0

 0&1=0

1&0=0

 1&1=1

|Binary OR

 0|0=0

 0|1=1

 1|0=1

 1|1=1

^Binary XOR

 0^0=0

 0^1=1

 1^0=1

 1^1=0

~Binary Ones ComplementIt is unary operator that flips bits.
<<Binary Left Shiftbits moved to left by specified places and adds trailing 0s
>>Binary Right Shiftbits moved to right by specified places and adds leading 0s
In [43]:
a,b=45,25
bin(a),bin(b)
Out[43]:
('0b101101', '0b11001')
In [44]:
#binary and
c=a&b
c, bin(c)
Out[44]:
(9, '0b1001')
In [45]:
#binary or
c=a|b
c, bin(c)
Out[45]:
(61, '0b111101')
In [46]:
#binary xor
c=a^b
c, bin(c)
Out[46]:
(52, '0b110100')
In [47]:
#binary complement
c=~a
c, bin(c)
Out[47]:
(-46, '-0b101110')
In [48]:
#left shift
c=a<<2
c, bin(c)
Out[48]:
(180, '0b10110100')
In [49]:
#right shift
c=a>>2
c, bin(c)
Out[49]:
(11, '0b1011')

Just to verify bitwise & operation on a and b by using truth table for & operator

a = 45 = 00101101
b = 25 = 00011001
-----------------------
a&b     = 00001001 = 9

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More