• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

In Out Code

Your comprehensive guide to optimized code

  • Data Structures
  • Python
    • Control Flow
    • HackerRank
    • Input and Output
    • Modules
  • AWS

Python Operators | Expert Guide with Code Samples

You are here: Home / Python / Operators / Python Operators | Expert Guide with Code Samples

May 20, 2019 by Daniel Andrews

What Are Python Operators?

Python operators are special symbols that are used to manipulate the value of operands, using arithmetic or logical computation. For example, in the expression 1 + 2 = 3, + is the operator, with 1 and 2 being the operands.

This guide walks you through the syntax and purpose of each python operator in detail, with clear, commented code samples.

The following types of operators are included:

  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Identity Operators
  • Logical Operators
  • Membership Operators

We’ve also added a quick guide to Python operator precedence, in case you need to chain together multiple operators in a single statement.


Python Arithmetic Operators

Arithmetic operators can be used to perform mathematical calculations, such as addition and subtraction, with numeric values.

OperatorNameDescriptionExample
+AdditionAdd right operand to left operand.1 + 2 (3)
-SubtractionSubtract right operand from left operand.4 - 2 (2)
*MultiplicationMultiply left operand by right operand.3 * 3 (9)
/DivisionDivide left operand by right operand.12 / 4 (3)
%ModulusDivide left operand by right operand. Return remainder.6 % 2 (0)
**ExponentiationExponential (power) calculation. Left operand to power of right operand.2 ** 3 (8)
//Floor DivisionFloor division of the left operand by right operand.5 // 2 (2)

Example of Arithmetic Operators

# Create variables and assign values using assignment operator '='
x = 10
y = 3

# Addition
print('x + y =', x + y)

# Subtraction
print('x - y =', x - y)

# Multiplication
print('x * y =', x * y)

# Division
print('x / y =', x / y)

# Floor Division
print('x // y =', x // y)

# Modulus
print('x % y =', x % y)

# Exponentiation
print('x ** y =', x ** y)
Output:
x + y = 13
x - y = 7
x * y = 30
x / y = 3.3333333333333335
x // y = 3
x % y = 1
x ** y = 1000

Python Assignment Operators

Python uses assignment operators to assign values to variables, such as x = 1. This also includes compound operators, such as +=.

With compound operators, the operation is performed on the variable, then the variable is assigned the new value. E.g. a += 1 is equivalent to a = a + 1.

For all compound operators, the equals sign is always on the right of the operator. E.g. +=, *=

OperatorDescriptionExampleSame As
=Simple assignment.x = 4x = 4
+=Add left and right operand values. x += 4x = x + 4
-=Subtract right operand from left operand.x -= 4x = x - 4
*=Multiply right operand by left operand.x *= 4x = x * 4
/=Divide left operand by right operand.x /= 4x = x / 4
%=Modulus of left operand to right operand.x %= 4x = x % 4
**=Power calculation for right operand to left operand.x **= 4x = x ** 4
//=Floor division of right operand by left operand.x //= 4x = x // 4
&=In-place bitwise andx &= 4x = x & 4
|=In-place bitwise orx |= 4x = x | 4
^=In-place bitwise xorx ^= 4x = x ^ 4
>>=In-place right shiftx >>= 4x = x >> 4
<<=In-place left shiftx <<= 4x = x << 4

In each of the above cases, the resulting value is assigned to the left operand.


Python Bitwise Operators

Bitwise operators handle operands as if they were in binary form, and operates bit by bit. E.g. 10 is 0000 1010 in binary.

OperatorNameDescription
&ANDSet each bit to 1 if both bits 1
|ORSet each bit to 1 if at least one of two bits is 1
^XORSets each bit to 1 if only one of two bits is 1
~NOTInvert the bits
<<Bitwise left shift(1)
>>Bitwise right shift(2)
(1) Shift left. Let leftmost bits drop off and push zeros in from the right. (2) Shift right. Let rightmost bits drop off and push copies of leftmost bit from the left.

Example of Bitwise Operators

# Create variables and assign values
x = 10 # 0000 1010 in binary
y = 7  # 0000 0111 in binary

# Bitwise AND
print('x & y =', x & y) # Expecting 2 (0000 0010)

# Bitwise OR
print('x | y =', x | y) # Expecting 15 (0000 1111)

# Bitwise XOR
print('x ^ y =', x ^ y) # Expecting 13 (0000 1101)

# Bitwise NOT
print('~ x =', ~ x) # Expecting -11 (1111 0101)

# Bitwise left shift
print('x << 2 =', x << 2) # Expecting 40 (0010 1000)

# Bitwise right shift
print('x >> 2 =', x >> 2) # Expecting 2 (0000 0010)
Output:
x & y = 2
x | y = 15
x ^ y = 13
~ x = -11
x << 2 = 40
x >> 2 = 2

Python Comparison Operators

Eight comparison operations are available in python, which are also known as relational operators.

Evaluated left to right, if at any point the condition is found to be false, the evaluation will not continue for additional comparisons.

You can also chain multiple comparison operators together in a single expression, which can yield better performance than two separate comparison operations. For example, a < b <= c is more efficient than a < b and b <= c, as b is only evaluated once.

Each has same priority Comparison operator priority is higher than boolean priority Objects of different types never compare equal. E.g. 1 == "1" will always be false. Also called relational operators.
OperatorNameExample
<Strictly less than.1 < 2 (True)
<=Less than or equal.2 <= 2 (True)
>Strictly greater than.4 > 2 (True)
>=Greater than or equal.5 >= 2 (True)
==Equal.4 == 3 (False)
!=Not equal.4 != 3 (True)
<>Not equal.4 <> 3 (True)

Example of Comparison Operators

# Create variables and assign values
x = 10
y = 3

# Greater Than
print('x > y =', x > y) # Expecting True

# Less Than
print('x < y =', x < y) # Expecting False

# Equal To
print('x == y =', x == y) # Expecting False

# Not Equal To
print('x != y =', x != y) # Expecting True

# Greater Than or Equal To
print('x >= y =', x >= y) # Expecting True

# Less Than or Equal To
print('x <= y =', x <= y) # Expecting False
Output:
x > y = True
x < y = False
x == y = False
x != y = True
x >= y = True
x <= y = False

Python Identity Operators

The two identity operators used in Python are is and is not. They return whether or not two objects are the same object in memory.

OperatorDescriptionExample
isIf two variables are the same object, return True.a = [1,2,3]
b = a
a is b (True)
is notIf variables are not the same object, return True. Otherwise False.a = [1,2,3]
b = [1,2,3]
a is not b (True)

Strings that are equal in value, are located in the same place in memory. The same is true of integers. Lists are located separately in memory, even if they contain the same collection of values.

Example of Python Identity Operators

# Create variables and assign values
x1 = 3
y1 = 3
x2 = "TestString"
y2 = "TestString"
x3 = ["val1","val2","val3", 1, 2]
y3 = ["val1","val2","val3", 1, 2]

# 'is' returning True
print('x1 is y1 =', x1 is y1)
print('x2 is y2 =', x2 is y2)

# 'is' returning False
print('x3 is y3 =', x3 is y3)

# 'is not' returning True
print('x3 is not y3 =', x3 is not y3)

# 'is not' returning False
print('x1 is not y1 =', x1 is not y1)
print('x2 is not y2 =', x2 is not y2)
Output:
x1 is y1 = True
x2 is y2 = True
x3 is y3 = False
x3 is not y3 = True
x1 is not y1 = False
x2 is not y2 = False

Python Logical Operators

Logical operators allow multiple conditional statements to be evaluated in a single expression.

OperatorDescriptionExample
andIf both statements are true, return True.2 < 5 and 5 < 10 (True)
orIf one of the statements is true, return True.2 < 5 or 5 < 2 (True)
notReturns the opposite of what the above two operators would return.not(2 < 5 and 5 < 10) (False)

With the and operator, if a conditional statement returns False, python will not evaluate future conditional statements in the expression. Likewise, with the or operator, if a conditional statement returns True, python will not evaluate future conditional statements in the expression.

Example using and

5 < 1 and 3 == 3. Python will never evaluate the second conditional statement (3 == 3), because the first conditional statement returned false.

Example using or

5 > 1 or 3 == 3. Python will never evaluate the second conditional statement (3 == 3), because the first conditional statement returned true.

Example of Logical Operators

# Create variables and assign values
x = True
y = False

# 'and' operator, returning True
print('x and x is', x and x)

# 'and' operator, returning False
print('x and y is', x and y)

# 'or' operator, returning True
print('x or y is', x or y)

# 'or' operator, returning False
print('y or y is', y or y)

# 'not' operator, returning True
print('not y is', not y)

# 'not' operator, returning False
print('not x is', not x)
Output:
x and x is True
x and y is False
x or y is True
y or y is False
not y is True
not x is False

Python Membership Operators

Python has two membership operators: in and not in. These operators test for membership of a sequence in an object, such as checking if string 'a' appears in the string sequence 'apple'.

Sequences where membership operators can be used are: lists, sets, strings, tuples and dictionaries (key presence only).

OperatorDescriptionExample
inIf specified value is found in the sequence, return True. Otherwise, returns False.a = 'a'
b = 'apple'
print(a in b)

This example returns a 1, as 'a' appears in 'apple'.
not inIf specified value is not found in the sequence, return True. Otherwise, returns False.a = 'x'
b = 'apple'
print(a not in b)

This example returns a 1, as 'x' does not appear in 'apple'.

Example of Membership Operators

# Create variables and assign values
x = "This is a test string"
y = {1:"x",2:"y"} # Create dictionary

# 'in' operator, returning True
print('"test" in x =', "test" in x)
print('"r" in x =', "r" in x)
print('1 in y =', 1 in y) # Test presence of value in dictionary keys

# 'in' operator, returning False
print('"this" in x =', "this" in x) # Fails due to Python being case sensitive
print('"q" in x =', "q" in x)
print('3 in y =', 3 in y) # Test presence of value in dictionary keys

# 'not in' operator, returning True
print('"failed" not in x =', "failed" not in x)
print('"q" not in x =', "q" not in x)
print('3 not in y =', 3 not in y) # Test presence of value in dictionary keys

# 'not in' operator, returning False
print('"test" not in x =', "test" not in x)
print('"r" not in x =', "r" not in x)
print('1 not in y =', 1 not in y) # Test presence of value in dictionary keys
Output:
"test" in x = True
"r" in x = True
1 in y = True
"this" in x = False
"q" in x = False
3 in y = False
"failed" not in x = True
"q" not in x = True
3 not in y = True
"test" not in x = False
"r" not in x = False
1 not in y = False

Python Operator Precedence

Operators are evaluated in order of precedence. It's important to remember this order, particularly when chaining together multiple operators in a single expression, if you want to be confident of the output.

PrecedenceOperatorDescription
1**Exponentiation
2~, +, -Complement, unary plus and minus
3*, /, %, //Multiply, divide, modulo and floor division
4+, -Addition and subtraction
5>>, <<Right and left bitwise shift
6&Bitwise 'AND'
7^, |Bitwise exclusive 'OR' and regular 'OR'
8<=, <>, >=Comparison operators
9<>, ==, !=Equality operators
10=, %=, /=, //=, -=, +=, *=, **=Assignment operators
11is, is notIdentity operators
12in, not inMembership operators
13not, or, andLogical operators

Category iconOperators

About Daniel Andrews

Passionate about all things data and cloud. Specializing in Python, AWS and DevOps, with a Masters degree in Data Science from City University, London, and a BSc in Computer Science.

Primary Sidebar

48-Hour Flash Sale. Online courses as low as $12.99

Categories

  • AWS (4)
  • Concepts (1)
  • Control Flow (1)
  • Data Structures (9)
  • HackerRank (1)
  • Input and Output (1)
  • LeetCode (1)
  • Modules (1)
  • Operators (1)
  • Python (2)
Udemy.com Homepage 300x250

Footer

Recent Posts

  • How to Setup Neo4j on AWS ECS (EC2)
  • How to Setup Neo4j on AWS EC2
  • How to List AWS S3 Bucket Names and Prefixes
  • Amazon Redshift Tutorial (AWS)
  • Big O: How to Calculate Time and Space Complexity

.