In this article, we’ll take a look at a dozen or so common operators in Python. In particular, we’re going to talk about several types of operators which mainly draw from mathematics. Hopefully, by the end of this article, you’ll have an appreciation for operators in Python!

## Table of Contents

## What Is An Operator?

In programming, **an operator is a symbolic representation of a function** like addition or concatenation. Usually, operators fall into three categories—logical, mathematical, and relational.

In terms of math operations, we have all the usual suspects like addition, subtraction, multiplication, and division. Each of these operations has a corresponding mathematical operator in Python: `+`, `-`, `*`, and `/`.

Naturally, all of the usual relational operations, such as greater than and less than, get the same treatment. Perhaps unsurprisingly, the operators line up nicely: `>`, `>=`, `==`, `<=`, `<`.

Finally, all the same logical operations that we discussed in our Crash Course in Computing for Python Beginners article exist as well. Of course, the Python developers went with the readability route on these operators and used their names directly: `and`, `or`, and `not`. Though, you could probably argue these aren’t operators at all. Typically, you’ll find them in their symbolic form in other languages (i.e. `&&`, `||`, `!`).

All that said, operators can really exist for any purpose. For instance, Python 3.9 will introduce the dictionary union operator for merging two dictionaries. Likewise, you’re probably already familiar with the assignment operator which we use to define variables. In the latter context, we actually know how to use the operator, but are all operators equal? In the next section, we’ll find out.

## How Do We Use An Operator?

In all this time talking about operators, we never actually discussed how they’re used. The reason for that is you probably already have working knowledge of operators without realizing it. For example, anyone familiar with arithmetic is going to find it very similar in Python:

>>> 5 + 7 12

That said, not all operators work the same way. To generalize, operators are classified by the number of operands (think inputs) they can accept. For most arithmetic operators, we expect them to handle two operands. In programming, we call them **binary operators** where “bi” refers to the number of operands rather than the number system we spoke about previously.

Of course, it’s possible for an operator to only work with one operand. For example, the subtraction operator can also be used to denote a negative number:

>>> -3 -3

We call this type of operator a **unary operator**, and they’re fairly common in most programming languages.

If you’re feeling especially adventurous, you might consider operators that work on more than two operands. For example, a lot of programming languages introduce a **ternary operator**, but we won’t explore them in this in article. If you’re interested in that sort of stuff, I found this article to be a decent read.

Now that we know how to use operators, I figured we’d take a moment to go through all of the most common operators in Python. First, however, we need to talk about a little black magic called **operator overloading**.

## Operator Overloading in Python

Throughout this article, we’ll be taking our time to discuss several common operators. Unfortunately, these operators aren’t as cut-and-dry as it may seem. That’s because Python allows for operator overloading which essentially allows us to change the behavior of certain operators—namely these ones (list is not exhaustive):

- Relational Operators: <, <=, ==, >=, >
- Mathematical Operators: +, -, *, /, //, %, **
- Augmented Mathematical Operators: +=, -=, *=, /=, //=, %=, **=

In other words, all of the operators in this list could be overloaded to provide a different behavior than expected. One of the most common ways we see this in Python is with the addition operator. Normally, we use the addition operator to add numbers together. However, it’s often used in Python in other convenient places like to combine strings or lists:

>>> "he" + "llo" 'hello' >>> [5] + [7] [5, 7]

While this wouldn’t be possible without the ability to overload operators, it does make things a bit more ambiguous—especially when we start working with variables. How do we know what the following code snippet does?

x + y

It’s really impossible to be sure without context. In fact, this line of code might even throw an error. After all, what if one of the values is a string and the other is an integer?

That said, for whatever we lose in clarity, we gain in brevity. In other words, sometimes having an operator can make it a lot easier to write concise code. For your sake, I’ll try to point out some examples when we start seeing more code in action. For now, however, we’ll get to the list of operators.

## Common Python Operators by Type

At this point, we should be comfortable with the concept of an operator. Now, we’ll take a look at some of the most common operators by type. In particular, we’ll be talking about the following classes of operators:

- Mathematical Operators
- Augmented Mathematical Operators
- Relational Operators
- Logical Oeprators

Ultimately, we’ll finish things out with a few bonus operators that I find useful.

### Mathematical Operators

As mentioned previously, there are a handful of common mathematical operators in Python:

Operation | Operator | Example |
---|---|---|

Addition | + | `5 + 6 # returns 11`python |

Subtraction | – | `8 – 13 # returns -5`python |

Multiplication | * | `4 * 3 # returns 12`python |

Division | / | `5 / 2 # returns 2.5`python |

Floor Division | // | `7 / 2 # returns 3`python |

Modulo | % | `15 % 4 # returns 2`python |

Power | ** | `2 ** 4 # returns 16`python |

Most of these operators need no explanation. However, there are a few worth mentioning.

#### Modulo

First and foremost, let’s talk about **modulo**. After all, if you’re truly a beginner, there’s a chance you’ve never heard of this operator. No worries! Despite its lack of popularity in arithmetic, the modulo operator is actually very common in programming because it allows us to perform clock arithmetic.

Clock arithmetic is this idea of treating numbers as if they’re bounded. In other words, rather than dealing with an infinite range of numbers, we can use clock arithmetic to bound our computation between zero and some other value (e.g. clocks rotate through 12 possible values).

For example, when a teacher wants to put students into groups of four, they ask students to count off by 4. Every time a student says 4, the next student starts again from 1. This is how clock arithmetic works—the range of values wraparound.

In Python, the modulo operator allows us to specify the size of our clock. For example, if we were to take a mathematical expression and mod it by 12, we would be able to determine where the hand would stop on a standard clock:

>>> 15 % 12 3

Clearly, this looks like some sort of conversion between 24-hour and 12-hour time, but we can go even further. For example, if we wanted to know what time it would 37 hours from now, we could figure it out:

>>> 9 + 37 % 12 10

Right now, it’s 9 o’clock. In 37 hours, it’ll be 10 o’clock. Certainly, that makes sense because every 12 hours we end up at the same time. In other words, 37 is divisible by 12 three times with a remainder of 1. That single hour is what pushes us over into 10 o’clock.

Another thing worth mentioning is that modulo often gets confused with remainder. While they’re not the same thing, they behave similarly in most cases—specifically positive integers. If you’re familiar with the remainder operator from languages like Java, be aware that the functionality is slightly different. If you’re interested in this difference, I’ve written about it in my article about the remainder operator in Java. Otherwise, let’s take a look at floor division.

#### Floor Division

While it’s probably worth mentioning how cool the power operator is, I don’t feel like there’s much to talk about. On the other hand, I think it’s worth closing out this section with a discussion about the **floor division** operator.

Previously in this series, I had mentioned that you should probably pick up Python 3 and abandon Python 2. After all, Python 2 has reached end of life. Well in that article, I mentioned that one of the differences between the two versions of the language was the addition of the floor division operator in Python 3.

In Python 3, numbers are about as abstract as they get in programming languages. For the most part, we don’t have to worry about overflow or the differences between integers and floating point values. And, I think this is great!

As a consequence, however, Python 3 had to introduce the floor division operator, so we could perform integer division (at least for positive values). Again, for new people picking up the language, there’s no need to worry about this nuance. That said, I think the history and context is important—especially if you decide to pick up pretty much any other language.

At any rate, the floor division operator divides two values normally then takes the floor of the result. If you’re unfamiliar with floor, it’s a rounding technique that rounds decimals down toward negative infinity. If you’re interested in learning more about rounding techniques, I wrote a whole article about rounding numbers in Python. Otherwise, let’s move on to the augmented mathematical operators.

### Augmented Mathematical Operators

One of the coolest features of any programming language is an augmented operator. At least by Python’s definition, an augmented operator performs function of a regular operator but also stores the result. Naturally, for an augmented operator to work, the left operand must be a variable:

>>> x = 10 >>> x += 5 >>> x 15

Here, we’ve stored the value 10 in the variable `x`python. Then, we added 5 to `x`python, so it now stores 15.

Now, the cool thing about this is it works for every mathematical operator. In other words, the same exact table from above can be place here with minimal changes:

Operation | Operator | Example |
---|---|---|

Augmented Addition | += | `x += 6`python |

Augmented Subtraction | -= | `x -= 13`python |

Augmented Multiplication | *= | `x *= 3`python |

Augmented Division | /= | `x /= 2`python |

Augmented Floor Division | //= | `x //= 2`python |

Augmented Modulo | %= | `x %= 4`python |

Augmented Power | **= | `x **= 4`python |

Since we already chatted about the operators once, I don’t think it makes sense to rehash them. In other words, let’s move on!

### Relational Operators

Another important set of operators are the relational operators. These include things like greater than and less than, and they’re used for comparing values. Here’s what they look like in action for numerical values:

Operation | Operator | Example |
---|---|---|

Less Than | < | `0 < 5 # returns True`python |

Less Than or Equals | <= | `9 <= 4 # returns False`python |

Equals | == | `3 == 3 # returns True`python |

Greater Than or Equals | >= | `-5 >= 5 # returns False`python |

Greater Than | > | `14 > 11 # returns True`python |

Not Equals | != | `2 != 2 # returns False`python |

While I find these operators relatively straightforward, there are two things worth mentioning.

First, I’d like to point out the distinction between the assignment operator (`=`) and the equality operator (`==`). When we want to define a variable, we use the assignment operator. When we want to compare two values for equality, we use the equality operator.

This distinction is often very confusing for new learners as they’re used to using the equals sign in mathematics. Fortunately, Python doesn’t allow the assignment operator to be used in an expression, so you’ll always get an error if you make this mistake:

>>> 5 = 7 SyntaxError: cannot assign to literal

That said, I always find it helpful to point this distinction out ahead of time. Perhaps it will prevent you from ever making that mistake in the first place!

Second, as I mentioned already, these operators can be and often are overloaded. In the table above, we use these operators to compare numeric values. However, these operators can be used in other contexts. For example, we can use this same set of operators to compare strings:

>>> "hi" < "yo" True

Again, this kind of ambiguity can make code a bit more difficult to read. That said, I prefer this syntax to something like `compareTo()`java from Java which is always a nightmare to use—hence why I think Kotlin introduced operator overloading.

Again, I’m going to stress that most of the operators mentioned in this article can be overloaded, so you can’t assume their behavior without context.

With that said, let’s take a look at the logical operators.

### Logical Operators

Honestly, I hesitated to include the logical operators because Python doesn’t really have them in the traditional sense. Normally, AND, OR, and NOT are represented using some symbolic representation akin to `&&`java, `||`java, and `!`java, respectively. Instead, Python opted for the following:

Operation | Operator | Example |
---|---|---|

AND | and | `True and True # returns True`python |

OR | or | `False or True # returns True`python |

NOT | not | `not False # returns True`python |

Because these aren’t really operators, we cannot overload them. In other words, they only work with **boolean expressions** (i.e. expressions that evaluate to True or False). Of course, Python let’s a lot of things evaluate to a boolean, but that’s probably a topic for another time. For now, let’s go ahead and close this list out with a discussion around a few miscellaneous operators.

### Miscellaneous Operators

Up to this point in the list, we’ve talked about the majority of the common operators which mostly come from mathematics and logic. Of course, there is so much more to programming than crunching numbers. Let’s take a look at some operators that break the mold:

#### Concatenation

Perhaps one of the most common operators in existence is concatenation which is a fancy word for combining two items in series. Usually, concatenation is used in the context of strings or lists, and it can be accomplished using the same operator as addition (`+`python):

>>> "Jeremy" + " Grifski" 'Jeremy Grifski'

In general, concatenation is considered bad practice because it’s fairly inefficient—at least for strings. That said, it’s an extremely popular operator, and you’re likely to see it all over the place including other popular programming languages.

#### Membership

Perviously in this article, I had mentioned that it’s hard to categorize the logical operators as operators. Well, there’s another similar operator in the bunch, `in`python, and it’s used to check if a collection contains an item. Take a look:

>>> x = [1, 2, 3] >>> 2 in x True

Here, we created a list that contains three numbers: 1, 2, and 3. Then, in the next line, we check if that list contains 2. Since it does, the program returns True.

This is one of those operators that’s incredibly useful but often forgotten—at least for me. I’m so used to using methods like `contains()`java that I forget about just how convenient Python actually is. For instance, look how convenient this is:

>>> "peach" in "123 peach avenue" True

Instead of writing a complex function to search this string for the substring, we can find it with ease using the `in`python keyword. How cool is that?! If you’re interested in seeing this operator in other contexts, here’s a few articles where I make use of it:

- How to Check If a Key Exists in a Dictionary in Python
- How to Check if a String Contains a Substring in Python

Otherwise, that’s it for operators! In the next section, we’ll talk about where we’re headed next.

## Knowledge Building

At this point in the series, we’re about 9 topics in. For some of you, this might seem unbearably slow. If that’s the case, I recommend pushing ahead (assuming those articles exist). That said, I think it’s important to take things slow and gain an appreciate for the field and the language. Hopefully, you feel like you’re building knowledge. I know I’ve learned a lot just writing this series.

With all that said, we’re going to slowly start working through Python syntax now. In the next article, we’ll start talking about how can get our programs to start making decisions (i.e. branching).

In the meantime, I’d appreciate it if you took the time to check out my list of ways to grow the site. Recently, I added my Discord while all the typical stuff remains (e.g. Newsletter, YouTube, Patreon, etc.).

If you can’t help that way, you can always keep reading:

- How to Create a List in Python: Loops, Comprehensions, and More
- How to Increment a Number in Python: Operators, Functions, and More

Likewise, here are some resources from the folks at Amazon (ad):

- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science

Otherwise, thanks for taking some time to check out the site. I hope you’re enjoying the series and will continue to follow it as it grows!