How to use operators in Python

Python operators are one of the most important components of the language to grasp. Here’s a basic guide to operators in Python to get you started.

How to use operators in Python
Picture by Domenico Loia, Unsplash.
16 minutes to read

For data scientists, Python operators are one of the most powerful and widely used features of this language. These special symbols or characters tell Python to perform some sort of operation, whether that’s multiplication, division, checking whether one item is greater than the other, or checking whether one value is present within another.

They cover a huge range of things - both used on their own, and when combined in more complex expressions. In this quick guide, we’ll go over the basics of Python operators, so you understand what they are, what they do, and how and where you can use them within your data science projects.

What are operators?

Operators are simply characters, or short sequences of characters, such as =, +, //, or and, that perform some kind of operation on values known as operands. When operands and operators are combined, they form something called an expression. This can be a simple as name = 'Bob' or total = 10 + 3, or it can be very complex and test for a whole range of things, or perform mathematical functions on loads of values.

There are seven main types of operator in Python, which are common to programming languages. They are: arithmetic or mathematical operators, comparison operators, assignment operators, bitwise operators, logical operators, identity operators, and membership operators.

Those found in Python may differ very slightly from operators found in other languages, so if you’re coming to Python from a different language beware that there may be some subtle differences to look out for.

Types of operator

Operator type Purpose
Arithmetic operators Arithmetic operators are used for performing mathematical functions on values, for example, multiplication, addition, subtraction, division, or exponentiation.
Comparison operators Comparison operators are used for comparing values to see if they are identical, different, greater than, less than, or other combinations of these.
Assignment operators Assignment operators are used to assign values to variables, often using a shorthand system which makes code more concise.
Bitwise operators Bitwise operators are used to compare numeric values.
Logical operators Logical operators are used to combine one or more conditional statements. For example, finding orders that are greater than £100 but less than £500.
Identity operators Identify operators are used to check whether you're dealing with two identical objects within your code.
Membership operators Membership operators check whether a value is in or not in an object, such as a list or string.

Arithmetic or mathematical operators

Arithmetic operators let you perform mathematical calculations within your code, so are among the most widely used operators by data scientists. These basic operators form the basis of all calculations, so you can do pretty much anything with them. The can be combined to calculate almost anything, but for speed you may wish to utilise a mathematical or statistical package, such as SciPy or NumPy, to perform common calculations. Note that Python doesn’t have the postfix operator for increment i++ or decrement i-- seen in other languages.

Operator Description Example
* The multiplication operator adds multiplies operands together. x * y
+ The addition operator adds two operands together. It can also be used as a unary plus. x + y
- The subtraction operator subtracts the right operand from the left. It can also be used as a unary minus. x * y
/ The division operator divides the left operand by the right operand and always returns a float. x / y
% The modulo or modulus operator returns the remainder of a division of the left operand over the right. x % y
// The floor division operator divides the left operand by the right and returns the floor value. x // y
** The exponent operator raises the left operand to the power of the right. x ** y

Examples of arithmetic operators

x = 10
y = 6

print('Multplication: x * y =',x * y)
print('Addition: x + y =',x + y)
print('Subtraction: x - y =',x - y)
print('Division: x / y =',x / y)
print('Modulus: x %% y =',x % y)
print('Floor division: x // y =',x // y)
print('Exponentiation: x ** y =',x ** y)
Multplication: x * y = 60
Addition: x + y = 16
Subtraction: x - y = 4
Division: x / y = 1.6666666666666667
Modulus: x %% y = 4
Floor division: x // y = 1
Exponentiation: x ** y = 1000000

Comparison operators

Comparison operators compare one value with another and return True or False accordingly. For example, you can use them to see if the value in the left operator is greater than the right, less than the right, equal to the one on the right, not equal to the one on the right, greater than or equal to the one on the right, or less than or equal to the one on the right. For more complex comparisons, you can also wrap these operators within parentheses.

Operator Description Example
> The greater than operator returns True if the left value is greater than the right. x > y
< The less than operator returns True if the left value is less than the right. x < y
== The equals operator returns True if both values are equal. x = y
!= The not equal to operator returns True if the values are not equal. x != y
>= The greater than or equal to operator returns True if the left value is greater than or equal to the right. x >= y
>= The less than or equal to operator returns True if the left value is less than or equal to the right. x <= y

Examples of comparison operators

x = 10
y = 6

print('Greater than: x > y =',x > y)
print('Less than: x < y =',x < y)
print('Equals: x = y =',x == y)
print('Not equal to: x != y =',x != y)
print('Greater than or equal to: x >= y =',x >= y)
print('Less than or equal to: x <= y =',x <= y)
Greater than: x > y = True
Less than: x < y = False
Equals: x = y = False
Not equal to: x != y = True
Greater than or equal to: x >= y = True
Less than or equal to: x <= y = False

Logical operators

Logical operators are extremely useful because they let you combine multiple statements or expressions to form a single more complex expression. There are only three of them - and, not, and or, but they are very powerful.

Operator Description Example
and The and operator returns True if both statements are true. x and y
not The not operator returns False if the result is true. not x
or The or operator returns true if either one of the statements is true. x or y

Examples of logical operators

x = True
y = False

print('and: x and y =',x and y)
print('or: x or y =',x or y)
print('not: not x =',not x)
and: x and y = False
or: x or y = True
not: not x = False

Identity operators

Identify operators are used to check whether you’re dealing with two identical objects within your code. The is operator returns True if both variables are the same object, while is not returns True if they’re different. Note that this also checks for the type not just the value, so the str 11 won’t match the int 11.

Operator Description Example
is The is operator returns True if both variables are the same object. x is y
is not The is not operator returns True if both variables are not the same object. x is not y

Examples of identity operators

a = 10
b = 10
c = 11
d = '11'
e = ['Dinesh', 'Richard', 'Gilfoyle']
f = ['Dinesh', 'Richard', 'Gilfoyle']

print('is: a is b =',a is b)
print('is: a is c =',a is c)
print('is: e is f =',c is d)
print('is: e is not f =',c is not d)
is: a is b = True
is: a is c = False
is: e is f = False
is: e is not f = True

Membership operators

The membership operators in and not in are used to find the presence of one value within another. For example, finding a particular value within a list, string, tuple, dictionary or set. They return a boolean value, i.e. True or False depending on whether the value is found or not. There are a couple of things to watch out for. For dictionaries, you can search only for the presence of the key, not the value, and all searches are case-sensitive.

Operator Description Example
in The in operator returns True if the left value is in the right object. x in y
not in The not in operator returns True if the left value is not in the right object. x not in y

Examples of membership operators

name = 'Richard Hendricks'
print('k' in name)
print('x' in name)
True
False
staff = ['Dinesh', 'Gilfoyle', 'Richard', 'Jared']
print('Gavin' in staff)
print('Gilfoyle' in staff)
False
True
companies = {1:'Pied Piper', 2:'Sliceline', 3:'Optimoji', 4:'K Hole Games'}
print('Hooli' not in companies)
print('Sliceline' not in companies)
print(2 not in companies)
True
True
False

Assignment operators

Assignment operators are arguably one of the most confusing types of operator within programming, as they’re not really as intuitive as most of the others. As the name implies, assignment operators are used to assign values to variables. For example, the most common one = assigns one value to another, so age = 40 sets the age variable to the value 40.

However, many are used mostly for shorthand. For example, x /= 10 is the same as writing x = x / 10. While some assignment operators bring conciseness, their drawback is that they are harder for other developers to process when they’re reading your code, so some teams prefer to avoid them in favour of clearer but longer expressions that are easier to decipher.

Operator Shorthand assignment Longhand equivalent
= x = 10 x = 10
+= x += 10 x = x + 10
-= x -= 10 x = x - 10
/= x /= 10 x = x / 10
*= x *= 10 x = x * 10
//= x //= 10 x = x // 10
%= x %= 10 x = x % 10
**= x **= 10 x = x ** 10
^= x ^= 10 x = x ^ 10
&= x &= 10 x = x & 10
|= x |= 10 x = x | 10
>>= x >>= 10 x = x >> 10
<<= x <<= 10 x = x << 10

Bitwise operators

Bitwise operators are probably the operators you’re least likely to use in everyday data science projects. They treat operand values as strings of binary digits, hence the bitwise name.

Operator Description
& The ampersand or bitwise AND operator
<< The double less than operator or bitwise left shift
>> The double greater than operator or bitwise right shift
| The pipe operator or bitwise OR
~ The tilde (or squiggle) operator is a bitiwse NOT and the only unary bitwise operator, so needs only one operand.
^ The caret (or hat) operator or bitwise XOR

Matt Clarke, Monday, March 08, 2021

Matt Clarke Matt is an Ecommerce and Marketing Director who uses data science to help in his work. Matt has a Master's degree in Internet Retailing (plus two other Master's degrees in different fields) and specialises in the technical side of ecommerce and marketing.