Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python assignment operators.

Assignment operators are used to assign values to variables:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Related Pages

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Assignment Operators

Add and assign, subtract and assign, multiply and assign, divide and assign, floor divide and assign, exponent and assign, modulo and assign.

to

to and assigns the result to

from and assigns the result to

by and assigns the result to

with and assigns the result to ; the result is always a float

with and assigns the result to ; the result will be dependent on the type of values used

to the power of and assigns the result to

is divided by and assigns the result to

For demonstration purposes, let’s use a single variable, num . Initially, we set num to 6. We can apply all of these operators to num and update it accordingly.

Assigning the value of 6 to num results in num being 6.

Expression: num = 6

Adding 3 to num and assigning the result back to num would result in 9.

Expression: num += 3

Subtracting 3 from num and assigning the result back to num would result in 6.

Expression: num -= 3

Multiplying num by 3 and assigning the result back to num would result in 18.

Expression: num *= 3

Dividing num by 3 and assigning the result back to num would result in 6.0 (always a float).

Expression: num /= 3

Performing floor division on num by 3 and assigning the result back to num would result in 2.

Expression: num //= 3

Raising num to the power of 3 and assigning the result back to num would result in 216.

Expression: num **= 3

Calculating the remainder when num is divided by 3 and assigning the result back to num would result in 2.

Expression: num %= 3

We can effectively put this into Python code, and you can experiment with the code yourself! Click the “Run” button to see the output.

The above code is useful when we want to update the same number. We can also use two different numbers and use the assignment operators to apply them on two different values.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

What are assignment expressions (using the "walrus" or ":=" operator)? Why was this syntax added?

Since Python 3.8, code can use the so-called "walrus" operator ( := ), documented in PEP 572 , for assignment expressions .

This seems like a really substantial new feature, since it allows this form of assignment within comprehensions and lambda s.

What exactly are the syntax, semantics, and grammar specifications of assignment expressions?

Why was this new (and seemingly quite radical) concept introduced, even though PEP 379 (which proposes the similar idea of "Adding an assignment expression") was withdrawn?

  • python-assignment-expression

Muhammad Dyas Yaskur's user avatar

  • 1 Are there organically-asked questions on this topic that can be closed with a link to this reference question? A question that might otherwise be approaching "too broad" can certainly be justifiable when it addresses what is otherwise a source of common duplicates. –  Charles Duffy Commented May 11, 2018 at 17:53
  • 18 This should be reopened. This is definitely not "too broad". It's a very specific subject and a very good reference question. –  Panagiotis Kanavos Commented Oct 5, 2018 at 16:27
  • 1 While it shouldn't be taken too literally because I'm sure Python may diverge in some ways, this is one of Go's best features and there are examples throughout the Go docs –  Brad Solomon Commented Apr 7, 2019 at 12:54
  • 8 Just to give you a historical perspective: A long and heated discussion among Python developers preceded the approval of PEP 572. And it appears to be one of the reasons why Guido resigned as BDFL. The assignment expressions have a number of valid usecases but can also be easily misused to make code less readable. Try to limit use of the walrus operator to clean cases that reduce complexity and improve readability. –  Jeyekomon Commented Oct 16, 2019 at 11:10
  • 1 For what it's worth: the earliest drafts of PEP 572 proposed the same kind of as syntax as in PEP 379. Although there was a lot of discussion and a huge amount of work done on the PEP, it was only about four and a half months from proposal to acceptance - some other PEPs have taken years. –  Karl Knechtel Commented Mar 27, 2023 at 1:26

6 Answers 6

PEP 572 contains many of the details, especially for the first question. I'll try to summarise/quote concisely arguably some of the most important parts of the PEP:

Allowing this form of assignment within comprehensions, such as list comprehensions, and lambda functions where traditional assignments are forbidden. This can also facilitate interactive debugging without the need for code refactoring.

Recommended use-case examples

A) getting conditional values.

for example (in Python 3):

can become:

while (command := input("> ")) != "quit": print("You entered:", command)

Similarly, from the docs :

In this example, the assignment expression helps avoid calling len() twice: if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)")

b) Simplifying list comprehensions

for example:

[(lambda y: [y, x/y])(x+1) for x in range(5)]
[[y := x+1, x/y] for x in range(5)]

Syntax and semantics

In any context where arbitrary Python expressions can be used, a named expression can appear. This is of the form name := expr where expr is any valid Python expression, and name is an identifier. The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value

Differences from regular assignment statements

In addition to being an expression rather than statement, there are several differences mentioned in the PEP: expression assignments go right-to-left, have different priority around commas, and do not support:

Multiple targets

x = y = z = 0 # Equivalent: (z := (y := (x := 0)))

Assignments not to a single name:

# No equivalent a[i] = x self.rest = []

Iterable packing/unpacking

# Equivalent needs extra parentheses loc = x, y # Use (loc := (x, y)) info = name, phone, *rest # Use (info := (name, phone, *rest)) # No equivalent px, py, pz = position name, phone, email, *other_info = contact

Inline type annotations:

# Closest equivalent is "p: Optional[int]" as a separate declaration p: Optional[int] = None

Augmented assignment is not supported:

total += tax # Equivalent: (total := total + tax)

wjandrea's user avatar

  • 3 You did not answer the most interesting part of your question: why was PEP 379 rejected and what is the difference between PEP 379 and PEP 572? –  paperskilltrees Commented Jul 2, 2023 at 16:09

A couple of my favorite examples of where assignment expressions can make code more concise and easier to read:

if statement

Infinite while statement.

There are other good examples in the PEP .

Jonathon Reinhart's user avatar

  • 12 Especially good examples: they show an aspect under which C sometimes managed to be clearer and more elegant than Python, I thought they were never going to fix this –  AquilaIrreale Commented Aug 15, 2019 at 19:21

A few more examples and rationales now that 3.8 has been officially released.

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Source: LicensedProfessional's reddit comment

Handle a matched regex
A loop that can't be trivially rewritten using 2-arg iter()
Reuse a value that's expensive to compute
Share a subexpression between a comprehension filter clause and its output

Charles Clayton's user avatar

  • does the (y := f(x)) have to be placed in the comprehension filter clause or can it be put in th output? Edit: just tested it and it works, i.e. you can do [(y := f(x)) for x in data if y is not None] –  awe lotta Commented Jan 14 at 4:54
What is := operator?

In simple terms := is a expression + assignment operator. it executes an expression and assigns the result of that expression in a single variable.

Why is := operator needed?

simple useful case will be to reduce function calls in comprehensions while maintaining the redability.

lets consider a list comprehension to add one and filter if result is grater than 0 without a := operator. Here we need to call the add_one function twice.

The result is as expected and we don't need to call the add_one function to call twice which shows the advantage of := operator

be cautious with walarus := operator while using list comprehension

below cases might help you better understand the use of := operator

Case 3: when a global variable is set to positive

Case 4: when a global variable is set to negitive

Pardhu's user avatar

Walrus operator can be used to avoid recomputation of some functions. Here is an example.

case 1: if complexOperation(num) > 90: result = complexOperation(num) executeActualFunctionality(result) case 2: if result := complexOperation(num) > 90: executeActualFunctionality(result)

In case 1, we are performing complexOperation() twice just because we are not sure of the result. This can be avoided by practicing case 2.

Note: we can also declare result variable before "IF loop" and compute complexOperation() once. But Python is all about decreasing number of lines

Tej Tarun Chintham's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python python-3.x python-3.8 python-assignment-expression or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • Bringing clarity to status tag usage on meta sites
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Is there any benefit to declaring an index that contains a primary key as unique?
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • What is the purpose of long plastic sleeve tubes around connections in appliances?
  • Big Transition of Binary Counting in perspective of IEEE754 floating point
  • If a friend hands me a marijuana edible then dies of a heart attack am I guilty of felony murder?
  • Remove spaces from the 3rd line onwards in a file on linux
  • Syntactically, who does Jesus refer to as 'to you' and 'those outside' in Mark 4:11?
  • Is there mathematical significance to the LaGuardia floor tiles?
  • How to fold or expand the wingtips on Boeing 777?
  • Why does each leg of my 240V outlet measure 125V to ground, but 217V across the hot wires?
  • Why is Stam Mishna attributed to R' Meir, a fourth-generation Tannah?
  • Is the white man at the other side of the Joliba river a historically identifiable person?
  • Do images have propositional content?
  • Sitecore headless on local environment experience editor facing issue
  • Can a V22 Osprey operate with only one propeller?
  • Overstaying knowing I have a new Schengen visa
  • Problem in solving an integral equation.
  • Safari causes high CPU load for no reason, launchservicesd active
  • How solid is the claim that Alfred Nobel found the Nobel Prize specifically because of his invention of dynamite?
  • Extract geometry information from a .shp file without the associated files
  • Can we use "day and night time" instead of "day and night"?
  • Model reduction in linear regression by stepwise elimination of predictors with "non-significant" coefficients
  • The quest for a Wiki-less Game
  • Has anyone returned from space in a different vehicle from the one they went up in? And if so who was the first?

assignment 4 python

  • DigitalOcean
  • Sign up for:

How To Use Assignment Expressions in Python

author

DavidMuller and Kathryn Hancox

How To Use Assignment Expressions in Python

The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

Introduction

Python 3.8 , released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called “the walrus operator” because := vaguely resembles a walrus with tusks.

Assignment expressions allow variable assignments to occur inside of larger expressions. While assignment expressions are never strictly necessary to write correct Python code, they can help make existing Python code more concise. For example, assignment expressions using the := syntax allow variables to be assigned inside of if statements , which can often produce shorter and more compact sections of Python code by eliminating variable assignments in lines preceding or following the if statement.

In this tutorial, you will use assignment expressions in several examples to produce concise sections of code.

Prerequisites

To get the most out of this tutorial, you will need:

Python 3.8 or above. Assignment expressions are a new feature added starting in Python 3.8. You can view the How To Install Python 3 and Set Up a Programming Environment on an Ubuntu 18.04 Server tutorial for help installing and upgrading Python.

The Python Interactive Console. If you would like to try out the example code in this tutorial you can use the How To Work with the Python Interactive Console tutorial.

Some familiarity with while loops, if statements, list comprehensions, and functions in Python 3 is useful, but not necessary. You can review our How To Code in Python 3 tutorial series for background knowledge.

Using Assignment Expressions in if Statements

Let’s start with an example of how you can use assignment expressions in an if statement.

Consider the following code that checks the length of a list and prints a statement:

If you run the previous code, you will receive the following output:

You initialize a list named some_list that contains three elements. Then, the if statement uses the assignment expression ((list_length := len(some_list)) to bind the variable named list_length to the length of some_list . The if statement evaluates to True because list_length is greater than 2 . You print a string using the list_length variable, which you bound initially with the assignment expression, indicating the the three-element list is too long.

Note: Assignment expressions are a new feature introduced in Python 3.8 . To run the examples in this tutorial, you will need to use Python 3.8 or higher.

Had we not used assignment expression, our code might have been slightly longer. For example:

This code sample is equivalent to the first example, but this code requires one extra standalone line to bind the value of list_length to len(some_list) .

Another equivalent code sample might just compute len(some_list) twice: once in the if statement and once in the print statement. This would avoid incurring the extra line required to bind a variable to the value of len(some_list) :

Assignment expressions help avoid the extra line or the double calculation.

Note: Assignment expressions are a helpful tool, but are not strictly necessary. Use your judgement and add assignment expressions to your code when it significantly improves the readability of a passage.

In the next section, we’ll explore using assignment expressions inside of while loops.

Using Assignment Expressions in while Loops

Assignment expressions often work well in while loops because they allow us to fold more context into the loop condition.

Consider the following example that embeds a user input function inside the while loop condition:

If you run this code, Python will continually prompt you for text input from your keyboard until you type the word stop . One example session might look like:

The assignment expression (directive := input("Enter text: ")) binds the value of directive to the value retrieved from the user via the input function. You bind the return value to the variable directive , which you print out in the body of the while loop. The while loop exits whenever the you type stop .

Had you not used an assignment expression, you might have written an equivalent input loop like:

This code is functionally identical to the one with assignment expressions, but requires four total lines (as opposed to two lines). It also duplicates the input("Enter text: ") call in two places. Certainly, there are many ways to write an equivalent while loop, but the assignment expression variant introduced earlier is compact and captures the program’s intention well.

So far, you’ve used assignment expression in if statements and while loops. In the next section, you’ll use an assignment expression inside of a list comprehension.

Using Assignment Expressions in List Comprehensions

We can also use assignment expressions in list comprehensions . List comprehensions allow you to build lists succinctly by iterating over a sequence and potentially adding elements to the list that satisfy some condition. Like list comprehensions, we can use assignment expressions to improve readability and make our code more concise.

Consider the following example that uses a list comprehension and an assignment expression to build a list of multiplied integers:

If you run the previous code, you will receive the following:

You define a function named slow_calculation that multiplies the given number x with itself. A list comprehension then iterates through 0 , 1 , and 2 returned by range(3) . An assignment expression binds the value result to the return of slow_calculation with i . You add the result to the newly built list as long as it is greater than 0. In this example, 0 , 1 , and 2 are all multiplied with themselves, but only the results 1 ( 1 * 1 ) and 4 ( 2 * 2 ) satisfy the greater than 0 condition and become part of the final list [1, 4] .

The slow_calculation function isn’t necessarily slow in absolute terms, but is meant to illustrate an important point about effeciency. Consider an alternate implementation of the previous example without assignment expressions:

Running this, you will receive the following output:

In this variant of the previous code, you use no assignment expressions. Instead, you call slow_calculation up to two times: once to ensure slow_calculation(i) is greater than 0 , and potentially a second time to add the result of the calculation to the final list. 0 is only multiplied with itself once because 0 * 0 is not greater than 0 . The other results, however, are doubly calculated because they satisfy the greater than 0 condition, and then have their results recalculated to become part of the final list [1, 4] .

You’ve now combined assignment expressions with list comprehensions to create blocks of code that are both efficient and concise.

In this tutorial, you used assignment expressions to make compact sections of Python code that assign values to variables inside of if statements, while loops, and list comprehensions.

For more information on other assignment expressions, you can view PEP 572 —the document that initially proposed adding assignment expressions to Python.

You may also want to check out our other Python content on our topic page .

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

Default avatar

Author of Intuitive Python

Check out Intuitive Python: Productive Development for Projects that Last

https://pragprog.com/titles/dmpython/intuitive-python/

Still looking for an answer?

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Creative Commons

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Popular Topics

  • Linux Basics
  • All tutorials
  • Talk to an expert

Join the Tech Talk

Please complete your information!

Featured on Community

assignment 4 python

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

assignment 4 python

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

assignment 4 python

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Featured Tutorials

Digitalocean products, welcome to the developer cloud.

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Python Tutorial

  • Python Basics
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators

Python - Assignment Operators

  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python Control Statements
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Python - OS Path Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Classes & Objects
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Built-in Exceptions
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - GUIs
  • Python Advanced Concepts
  • Python - Abstract Base Classes
  • Python - Custom Exceptions
  • Python - Higher Order Functions
  • Python - Object Internals
  • Python - Memory Management
  • Python - Metaclasses
  • Python - Metaprogramming with Metaclasses
  • Python - Mocking and Stubbing
  • Python - Monkey Patching
  • Python - Signal Handling
  • Python - Type Hints
  • Python - Automation Tutorial
  • Python - Humanize Package
  • Python - Context Managers
  • Python - Coroutines
  • Python - Descriptors
  • Python - Diagnosing and Fixing Memory Leaks
  • Python - Immutable Data Structures
  • Python Useful Resources
  • Python - Questions & Answers
  • Python - Online Quiz
  • Python - Quick Guide
  • Python - Projects
  • Python - Useful Resources
  • Python - Discussion
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python Assignment Operator

The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left. The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the expressions on the either side of the symbol are equal.

Example of Assignment Operator in Python

Consider following Python statements −

At the first instance, at least for somebody new to programming but who knows maths, the statement "a=a+b" looks strange. How could a be equal to "a+b"? However, it needs to be reemphasized that the = symbol is an assignment operator here and not used to show the equality of LHS and RHS.

Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.

In the statement "a+=b", the two operators "+" and "=" can be combined in a "+=" operator. It is called as add and assign operator. In a single statement, it performs addition of two operands "a" and "b", and result is assigned to operand on left, i.e., "a".

Augmented Assignment Operators in Python

In addition to the simple assignment operator, Python provides few more assignment operators for advanced use. They are called cumulative or augmented assignment operators. In this chapter, we shall learn to use augmented assignment operators defined in Python.

Python has the augmented assignment operators for all arithmetic and comparison operators.

Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands may be of different types. However, the type of left operand changes to the operand of on right, if it is wider.

The += operator is an augmented operator. It is also called cumulative addition operator, as it adds "b" in "a" and assigns the result back to a variable.

The following are the augmented assignment operators in Python:

  • Augmented Addition Operator
  • Augmented Subtraction Operator
  • Augmented Multiplication Operator
  • Augmented Division Operator
  • Augmented Modulus Operator
  • Augmented Exponent Operator
  • Augmented Floor division Operator

Augmented Addition Operator (+=)

Following examples will help in understanding how the "+=" operator works −

It will produce the following output −

Augmented Subtraction Operator (-=)

Use -= symbol to perform subtract and assign operations in a single statement. The "a-=b" statement performs "a=a-b" assignment. Operands may be of any number type. Python performs implicit type casting on the object which is narrower in size.

Augmented Multiplication Operator (*=)

The "*=" operator works on similar principle. "a*=b" performs multiply and assign operations, and is equivalent to "a=a*b". In case of augmented multiplication of two complex numbers, the rule of multiplication as discussed in the previous chapter is applicable.

Augmented Division Operator (/=)

The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is equivalent to "a=a/b". The division operation of int or float operands is float. Division of two complex numbers returns a complex number. Given below are examples of augmented division operator.

Augmented Modulus Operator (%=)

To perform modulus and assignment operation in a single statement, use the %= operator. Like the mod operator, its augmented version also is not supported for complex number.

Augmented Exponent Operator (**=)

The "**=" operator results in computation of "a" raised to "b", and assigning the value back to "a". Given below are some examples −

Augmented Floor division Operator (//=)

For performing floor division and assignment in a single statement, use the "//=" operator. "a//=b" is equivalent to "a=a//b". This operator cannot be used with complex numbers.

Operators and Expressions in Python

Operators and Expressions in Python

Table of Contents

Getting Started With Operators and Expressions

The assignment operator and statements, arithmetic operators and expressions in python, comparison of integer values, comparison of floating-point values, comparison of strings, comparison of lists and tuples, boolean expressions involving boolean operands, evaluation of regular objects in a boolean context, boolean expressions involving other types of operands, compound logical expressions and short-circuit evaluation, idioms that exploit short-circuit evaluation, compound vs chained expressions, conditional expressions or the ternary operator, identity operators and expressions in python, membership operators and expressions in python, concatenation and repetition operators and expressions, the walrus operator and assignment expressions, bitwise operators and expressions in python, operator precedence in python, augmented assignment operators and expressions.

In Python, operators are special symbols, combinations of symbols, or keywords that designate some type of computation. You can combine objects and operators to build expressions that perform the actual computation. So, operators are the building blocks of expressions, which you can use to manipulate your data. Therefore, understanding how operators work in Python is essential for you as a programmer.

In this tutorial, you’ll learn about the operators that Python currently supports. You’ll also learn the basics of how to use these operators to build expressions.

In this tutorial, you’ll:

  • Get to know Python’s arithmetic operators and use them to build arithmetic expressions
  • Explore Python’s comparison , Boolean , identity , and membership operators
  • Build expressions with comparison, Boolean, identity, and membership operators
  • Learn about Python’s bitwise operators and how to use them
  • Combine and repeat sequences using the concatenation and repetition operators
  • Understand the augmented assignment operators and how they work

To get the most out of this tutorial, you should have a basic understanding of Python programming concepts, such as variables , assignments , and built-in data types .

Free Bonus: Click here to download your comprehensive cheat sheet covering the various operators in Python.

Take the Quiz: Test your knowledge with our interactive “Python Operators and Expressions” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Test your understanding of Python operators and expressions.

In programming, an operator is usually a symbol or combination of symbols that allows you to perform a specific operation. This operation can act on one or more operands . If the operation involves a single operand, then the operator is unary . If the operator involves two operands, then the operator is binary .

For example, in Python, you can use the minus sign ( - ) as a unary operator to declare a negative number. You can also use it to subtract two numbers:

In this code snippet, the minus sign ( - ) in the first example is a unary operator, and the number 273.15 is the operand. In the second example, the same symbol is a binary operator, and the numbers 5 and 2 are its left and right operands.

Programming languages typically have operators built in as part of their syntax. In many languages, including Python, you can also create your own operator or modify the behavior of existing ones, which is a powerful and advanced feature to have.

In practice, operators provide a quick shortcut for you to manipulate data, perform mathematical calculations, compare values, run Boolean tests, assign values to variables, and more. In Python, an operator may be a symbol, a combination of symbols, or a keyword , depending on the type of operator that you’re dealing with.

For example, you’ve already seen the subtraction operator, which is represented with a single minus sign ( - ). The equality operator is a double equal sign ( == ). So, it’s a combination of symbols:

In this example, you use the Python equality operator ( == ) to compare two numbers. As a result, you get True , which is one of Python’s Boolean values.

Speaking of Boolean values, the Boolean or logical operators in Python are keywords rather than signs, as you’ll learn in the section about Boolean operators and expressions . So, instead of the odd signs like || , && , and ! that many other programming languages use, Python uses or , and , and not .

Using keywords instead of odd signs is a really cool design decision that’s consistent with the fact that Python loves and encourages code’s readability .

You’ll find several categories or groups of operators in Python. Here’s a quick list of those categories:

  • Assignment operators
  • Arithmetic operators
  • Comparison operators
  • Boolean or logical operators
  • Identity operators
  • Membership operators
  • Concatenation and repetition operators
  • Bitwise operators

All these types of operators take care of specific types of computations and data-processing tasks. You’ll learn more about these categories throughout this tutorial. However, before jumping into more practical discussions, you need to know that the most elementary goal of an operator is to be part of an expression . Operators by themselves don’t do much:

As you can see in this code snippet, if you use an operator without the required operands, then you’ll get a syntax error . So, operators must be part of expressions, which you can build using Python objects as operands.

So, what is an expression anyway? Python has simple and compound statements. A simple statement is a construct that occupies a single logical line , like an assignment statement. A compound statement is a construct that occupies multiple logical lines, such as a for loop or a conditional statement. An expression is a simple statement that produces and returns a value.

You’ll find operators in many expressions. Here are a few examples:

In the first two examples, you use the addition and division operators to construct two arithmetic expressions whose operands are integer numbers. In the last example, you use the equality operator to create a comparison expression. In all cases, you get a specific value after executing the expression.

Note that not all expressions use operators. For example, a bare function call is an expression that doesn’t require any operator:

In the first example, you call the built-in abs() function to get the absolute value of -7 . Then, you compute 2 to the power of 8 using the built-in pow() function. These function calls occupy a single logical line and return a value. So, they’re expressions.

Finally, the call to the built-in print() function is another expression. This time, the function doesn’t return a fruitful value, but it still returns None , which is the Python null type . So, the call is technically an expression.

Note: All Python functions have a return value, either explicit or implicit. If you don’t provide an explicit return statement when defining a function, then Python will automatically make the function return None .

Even though all expressions are statements, not all statements are expressions. For example, pure assignment statements don’t return any value, as you’ll learn in a moment. Therefore, they’re not expressions. The assignment operator is a special operator that doesn’t create an expression but a statement.

Note: Since version 3.8, Python also has what it calls assignment expressions. These are special types of assignments that do return a value. You’ll learn more about this topic in the section The Walrus Operator and Assignment Expressions .

Okay! That was a quick introduction to operators and expressions in Python. Now it’s time to dive deeper into the topic. To kick things off, you’ll start with the assignment operator and statements.

The assignment operator is one of the most frequently used operators in Python. The operator consists of a single equal sign ( = ), and it operates on two operands. The left-hand operand is typically a variable , while the right-hand operand is an expression.

Note: As you already learned, the assignment operator doesn’t create an expression. Instead, it creates a statement that doesn’t return any value.

The assignment operator allows you to assign values to variables . Strictly speaking, in Python, this operator makes variables or names refer to specific objects in your computer’s memory. In other words, an assignment creates a reference to a concrete object and attaches that reference to the target variable.

Note: To dive deeper into using the assignment operator, check out Python’s Assignment Operator: Write Robust Assignments .

For example, all the statements below create new variables that hold references to specific objects:

In the first statement, you create the number variable, which holds a reference to the number 42 in your computer’s memory. You can also say that the name number points to 42 , which is a concrete object.

In the rest of the examples, you create other variables that point to other types of objects, such as a string , tuple , and list , respectively.

You’ll use the assignment operator in many of the examples that you’ll write throughout this tutorial. More importantly, you’ll use this operator many times in your own code. It’ll be your forever friend. Now you can dive into other Python operators!

Arithmetic operators are those operators that allow you to perform arithmetic operations on numeric values. Yes, they come from math, and in most cases, you’ll represent them with the usual math signs. The following table lists the arithmetic operators that Python currently supports:

Operator Type Operation Sample Expression Result
Unary Positive without any transformation since this is simply a complement to negation
Binary Addition The arithmetic sum of and
Unary Negation The value of but with the opposite sign
Binary Subtraction subtracted from
Binary Multiplication The product of and
Binary Division The quotient of divided by , expressed as a float
Binary Modulo The remainder of divided by
Binary Floor division or integer division The quotient of divided by , rounded to the next smallest whole number
Binary Exponentiation raised to the power of

Note that a and b in the Sample Expression column represent numeric values, such as integer , floating-point , complex , rational , and decimal numbers.

Here are some examples of these operators in use:

In this code snippet, you first create two new variables, a and b , holding 5 and 2 , respectively. Then you use these variables to create different arithmetic expressions using a specific operator in each expression.

Note: The Python REPL will display the return value of an expression as a way to provide immediate feedback to you. So, when you’re in an interactive session, you don’t need to use the print() function to check the result of an expression. You can just type in the expression and press Enter to get the result.

Again, the standard division operator ( / ) always returns a floating-point number, even if the dividend is evenly divisible by the divisor:

In the first example, 10 is evenly divisible by 5 . Therefore, this operation could return the integer 2 . However, it returns the floating-point number 2.0 . In the second example, 10.0 is a floating-point number, and 5 is an integer. In this case, Python internally promotes 5 to 5.0 and runs the division. The result is a floating-point number too.

Note: With complex numbers, the division operator doesn’t return a floating-point number but a complex one:

Here, you run a division between an integer and a complex number. In this case, the standard division operator returns a complex number.

Finally, consider the following examples of using the floor division ( // ) operator:

Floor division always rounds down . This means that the result is the greatest integer that’s smaller than or equal to the quotient. For positive numbers, it’s as though the fractional portion is truncated, leaving only the integer portion.

Comparison Operators and Expressions in Python

The Python comparison operators allow you to compare numerical values and any other objects that support them. The table below lists all the currently available comparison operators in Python:

Operator Operation Sample Expression Result
Equal to • if the value of is equal to the value of
• otherwise
Not equal to • if isn’t equal to
• otherwise
Less than • if is less than
• otherwise
Less than or equal to • if is less than or equal to
• otherwise
Greater than • if is greater than
• otherwise
Greater than or equal to • if is greater than or equal to
• otherwise

The comparison operators are all binary. This means that they require left and right operands. These operators always return a Boolean value ( True or False ) that depends on the truth value of the comparison at hand.

Note that comparisons between objects of different data types often don’t make sense and sometimes aren’t allowed in Python. For example, you can compare a number and a string for equality with the == operator. However, you’ll get False as a result:

The integer 2 isn’t equal to the string "2" . Therefore, you get False as a result. You can also use the != operator in the above expression, in which case you’ll get True as a result.

Non-equality comparisons between operands of different data types raise a TypeError exception:

In this example, Python raises a TypeError exception because a less than comparison ( < ) doesn’t make sense between an integer and a string. So, the operation isn’t allowed.

It’s important to note that in the context of comparisons, integer and floating-point values are compatible, and you can compare them.

You’ll typically use and find comparison operators in Boolean contexts like conditional statements and while loops . They allow you to make decisions and define a program’s control flow .

The comparison operators work on several types of operands, such as numbers, strings, tuples, and lists. In the following sections, you’ll explore the differences.

Probably, the more straightforward comparisons in Python and in math are those involving integer numbers. They allow you to count real objects, which is a familiar day-to-day task. In fact, the non-negative integers are also called natural numbers . So, comparing this type of number is probably pretty intuitive, and doing so in Python is no exception.

Consider the following examples that compare integer numbers:

In the first set of examples, you define two variables, a and b , to run a few comparisons between them. The value of a is less than the value of b . So, every comparison expression returns the expected Boolean value. The second set of examples uses two values that are equal, and again, you get the expected results.

Comparing floating-point numbers is a bit more complicated than comparing integers. The value stored in a float object may not be precisely what you’d think it would be. For that reason, it’s bad practice to compare floating-point values for exact equality using the == operator.

Consider the example below:

Yikes! The internal representation of this addition isn’t exactly equal to 3.3 , as you can see in the final example. So, comparing x to 3.3 with the equality operator returns False .

To compare floating-point numbers for equality, you need to use a different approach. The preferred way to determine whether two floating-point values are equal is to determine whether they’re close to one another, given some tolerance.

The math module from the standard library provides a function conveniently called isclose() that will help you with float comparison. The function takes two numbers and tests them for approximate equality:

In this example, you use the isclose() function to compare x and 3.3 for approximate equality. This time, you get True as a result because both numbers are close enough to be considered equal.

For further details on using isclose() , check out the Find the Closeness of Numbers With Python isclose() section in The Python math Module: Everything You Need to Know .

You can also use the comparison operators to compare Python strings in your code. In this context, you need to be aware of how Python internally compares string objects. In practice, Python compares strings character by character using each character’s Unicode code point . Unicode is Python’s default character set .

You can use the built-in ord() function to learn the Unicode code point of any character in Python. Consider the following examples:

The uppercase "A" has a lower Unicode point than the lowercase "a" . So, "A" is less than "a" . In the end, Python compares characters using integer numbers. So, the same rules that Python uses to compare integers apply to string comparison.

When it comes to strings with several characters, Python runs the comparison character by character in a loop.

The comparison uses lexicographical ordering , which means that Python compares the first item from each string. If their Unicode code points are different, this difference determines the comparison result. If the Unicode code points are equal, then Python compares the next two characters, and so on, until either string is exhausted:

In this example, Python compares both operands character by character. When it reaches the end of the string, it compares "o" and "O" . Because the lowercase letter has a greater Unicode code point, the first version of the string is greater than the second.

You can also compare strings of different lengths:

In this example, Python runs a character-by-character comparison as usual. If it runs out of characters, then the shorter string is less than the longer one. This also means that the empty string is the smallest possible string.

In your Python journey, you can also face the need to compare lists with other lists and tuples with other tuples. These data types also support the standard comparison operators. Like with strings, when you use a comparison operator to compare two lists or two tuples, Python runs an item-by-item comparison.

Note that Python applies specific rules depending on the type of the contained items. Here are some examples that compare lists and tuples of integer values:

In these examples, you compare lists and tuples of numbers using the standard comparison operators. When comparing these data types, Python runs an item-by-item comparison.

For example, in the first expression above, Python compares the 2 in the left operand and the 2 in the right operand. Because they’re equal, Python continues comparing 3 and 3 to conclude that both lists are equal. The same thing happens in the second example, where you compare tuples containing the same data.

It’s important to note that you can actually compare lists to tuples using the == and != operators. However, you can’t compare lists and tuples using the < , > , <= , and >= operators:

Python supports equality comparison between lists and tuples. However, it doesn’t support the rest of the comparison operators, as you can conclude from the final two examples. If you try to use them, then you get a TypeError telling you that the operation isn’t supported.

You can also compare lists and tuples of different lengths:

In the first two examples, you get True as a result because 5 is less than 8 . That fact is sufficient for Python to solve the comparison. In the second pair of examples, you get False . This result makes sense because the compared sequences don’t have the same length, so they can’t be equal.

In the final pair of examples, Python compares 5 with 5 . They’re equal, so the comparison continues. Because there are no more values to compare in the right-hand operands, Python concludes that the left-hand operands are greater.

As you can see, comparing lists and tuples can be tricky. It’s also an expensive operation that, in the worst case, requires traversing two entire sequences. Things get more complex and expensive when the contained items are also sequences. In those situations, Python will also have to compare items in a value-by-value manner, which adds cost to the operation.

Boolean Operators and Expressions in Python

Python has three Boolean or logical operators: and , or , and not . They define a set of operations denoted by the generic operators AND , OR , and NOT . With these operators, you can create compound conditions.

In the following sections, you’ll learn how the Python Boolean operators work. Especially, you’ll learn that some of them behave differently when you use them with Boolean values or with regular objects as operands.

You’ll find many objects and expressions that are of Boolean type or bool , as Python calls this type. In other words, many objects evaluate to True or False , which are the Python Boolean values.

For example, when you evaluate an expression using a comparison operator, the result of that expression is always of bool type:

In this example, the expression age > 18 returns a Boolean value, which you store in the is_adult variable. Now is_adult is of bool type, as you can see after calling the built-in type() function.

You can also find Python built-in and custom functions that return a Boolean value. This type of function is known as a predicate function. The built-in all() , any() , callable() , and isinstance() functions are all good examples of this practice.

Consider the following examples:

In this code snippet, you first define a variable called number using your old friend the assignment operator. Then you create another variable called validation_conditions . This variable holds a tuple of expressions. The first expression uses isinstance() to check whether number is an integer value.

The second is a compound expression that combines the modulo ( % ) and equality ( == ) operators to create a condition that checks whether the input value is an even number. In this condition, the modulo operator returns the remainder of dividing number by 2 , and the equality operator compares the result with 0 , returning True or False as the comparison’s result.

Then you use the all() function to determine if all the conditions are true. In this example, because number = 42 , the conditions are true, and all() returns True . You can play with the value of number if you’d like to experiment a bit.

In the final two examples, you use the callable() function. As its name suggests, this function allows you to determine whether an object is callable . Being callable means that you can call the object with a pair of parentheses and appropriate arguments, as you’d call any Python function.

The number variable isn’t callable, and the function returns False , accordingly. In contrast, the print() function is callable, so callable() returns True .

All the previous discussion is the basis for understanding how the Python logical operators work with Boolean operands.

Logical expressions involving and , or , and not are straightforward when the operands are Boolean. Here’s a summary. Note that x and y represent Boolean operands:

Operator Sample Expression Result
• if both and are
• otherwise
• if either or is
• otherwise
• if is
• if is

This table summarizes the truth value of expressions that you can create using the logical operators with Boolean operands. There’s something to note in this summary. Unlike and and or , which are binary operators, the not operator is unary, meaning that it operates on one operand. This operand must always be on the right side.

Now it’s time to take a look at how the operators work in practice. Here are a few examples of using the and operator with Boolean operands:

In the first example, both operands return True . Therefore, the and expression returns True as a result. In the second example, the left-hand operand is True , but the right-hand operand is False . Because of this, the and operator returns False .

In the third example, the left-hand operand is False . In this case, the and operator immediately returns False and never evaluates the 3 == 3 condition. This behavior is called short-circuit evaluation . You’ll learn more about it in a moment.

Note: Short-circuit evaluation is also called McCarthy evaluation in honor of computer scientist John McCarthy .

In the final example, both conditions return False . Again, and returns False as a result. However, because of the short-circuit evaluation, the right-hand expression isn’t evaluated.

What about the or operator? Here are a few examples that demonstrate how it works:

In the first three examples, at least one of the conditions returns True . In all cases, the or operator returns True . Note that if the left-hand operand is True , then or applies short-circuit evaluation and doesn’t evaluate the right-hand operand. This makes sense. If the left-hand operand is True , then or already knows the final result. Why would it need to continue the evaluation if the result won’t change?

In the final example, both operands are False , and this is the only situation where or returns False . It’s important to note that if the left-hand operand is False , then or has to evaluate the right-hand operand to arrive at a final conclusion.

Finally, you have the not operator, which negates the current truth value of an object or expression:

If you place not before an expression, then you get the inverse truth value. When the expression returns True , you get False . When the expression evaluates to False , you get True .

There is a fundamental behavior distinction between not and the other two Boolean operators. In a not expression, you always get a Boolean value as a result. That’s not always the rule that governs and and or expressions, as you’ll learn in the Boolean Expressions Involving Other Types of Operands section.

In practice, most Python objects and expressions aren’t Boolean. In other words, most objects and expressions don’t have a True or False value but a different type of value. However, you can use any Python object in a Boolean context, such as a conditional statement or a while loop.

In Python, all objects have a specific truth value. So, you can use the logical operators with all types of operands.

Python has well-established rules to determine the truth value of an object when you use that object in a Boolean context or as an operand in an expression built with logical operators. Here’s what the documentation says about this topic:

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false: constants defined to be false: None and False . zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1) empty sequences and collections: '' , () , [] , {} , set() , range(0) ( Source )

You can determine the truth value of an object by calling the built-in bool() function with that object as an argument. If bool() returns True , then the object is truthy . If bool() returns False , then it’s falsy .

For numeric values, you have that a zero value is falsy, while a non-zero value is truthy:

Python considers the zero value of all numeric types falsy. All the other values are truthy, regardless of how close to zero they are.

Note: Instead of a function, bool() is a class. However, because Python developers typically use this class as a function, you’ll find that most people refer to it as a function rather than as a class. Additionally, the documentation lists this class on the built-in functions page. This is one of those cases where practicality beats purity .

When it comes to evaluating strings, you have that an empty string is always falsy, while a non-empty string is truthy:

Note that strings containing white spaces are also truthy in Python’s eyes. So, don’t confuse empty strings with whitespace strings.

Finally, built-in container data types, such as lists, tuples, sets , and dictionaries , are falsy when they’re empty. Otherwise, Python considers them truthy objects:

To determine the truth value of container data types, Python relies on the .__len__() special method . This method provides support for the built-in len() function, which you can use to determine the number of items in a given container.

In general, if .__len__() returns 0 , then Python considers the container a falsy object, which is consistent with the general rules you’ve just learned before.

All the discussion about the truth value of Python objects in this section is key to understanding how the logical operators behave when they take arbitrary objects as operands.

You can also use any objects, such as numbers or strings, as operands to and , or , and not . You can even use combinations of a Boolean object and a regular one. In these situations, the result depends on the truth value of the operands.

Note: Boolean expressions that combine two Boolean operands are a special case of a more general rule that allows you to use the logical operators with all kinds of operands. In every case, you’ll get one of the operands as a result.

You’ve already learned how Python determines the truth value of objects. So, you’re ready to dive into creating expressions with logic operators and regular objects.

To start off, below is a table that summarizes what you get when you use two objects, x and y , in an and expression:

If is returns
Truthy
Falsy

It’s important to emphasize a subtle detail in the above table. When you use and in an expression, you don’t always get True or False as a result. Instead, you get one of the operands. You only get True or False if the returned operand has either of these values.

Here are some code examples that use integer values. Remember that in Python, the zero value of numeric types is falsy. The rest of the values are truthy:

In the first expression, the left-hand operand ( 3 ) is truthy. So, you get the right-hand operand ( 4 ) as a result.

In the second example, the left-hand operand ( 0 ) is falsy, and you get it as a result. In this case, Python applies the short-circuit evaluation technique. It already knows that the whole expression is false because 0 is falsy, so Python returns 0 immediately without evaluating the right-hand operand.

In the final expression, the left-hand operand ( 3 ) is truthy. Therefore Python needs to evaluate the right-hand operand to make a conclusion. As a result, you get the right-hand operand, no matter what its truth value is.

Note: To dive deeper into the and operator, check out Using the “and” Boolean Operator in Python .

When it comes to using the or operator, you also get one of the operands as a result. This is what happens for two arbitrary objects, x and y :

Again, the expression x or y doesn’t evaluate to either True or False . Instead, it returns one of its operands, x or y .

As you can conclude from the above table, if the left-hand operand is truthy, then you get it as a result. Otherwise, you get the second operand. Here are some examples that demonstrate this behavior:

In the first example, the left-hand operand is truthy, and or immediately returns it. In this case, Python doesn’t evaluate the second operand because it already knows the final result. In the second example, the left-hand operand is falsy, and Python has to evaluate the right-hand one to determine the result.

In the last example, the left-hand operand is truthy, and that fact defines the result of the expression. There’s no need to evaluate the right-hand operand.

An expression like x or y is truthy if either x or y is truthy, and falsy if both x and y are falsy. This type of expression returns the first truthy operand that it finds. If both operands are falsy, then the expression returns the right-hand operand. To see this latter behavior in action, consider the following example:

In this specific expression, both operands are falsy. So, the or operator returns the right-hand operand, and the whole expression is falsy as a result.

Note: To learn more about the or operator, check out Using the “or” Boolean Operator in Python .

Finally, you have the not operator. You can also use this one with any object as an operand. Here’s what happens:

The not operator has a uniform behavior. It always returns a Boolean value. This behavior differs from its sibling operators, and and or .

Here are some code examples:

In the first example, the operand, 3 , is truthy from Python’s point of view. So, the operator returns False . In the second example, the operand is falsy, and not returns True .

Note: To better understand the not operator, check out Using the “not” Boolean Operator in Python .

In summary, the Python not operator negates the truth value of an object and always returns a Boolean value. This latter behavior differs from the behavior of its sibling operators and and or , which return operands rather than Boolean values.

So far, you’ve seen expressions with only a single or or and operator and two operands. However, you can also create compound logical expressions with multiple logical operators and operands.

To illustrate how to create a compound expression using or , consider the following toy example:

This expression returns the first truthy value. If all the preceding x variables are falsy, then the expression returns the last value, xn .

Note: In an expression like the one above, Python uses short-circuit evaluation . The operands are evaluated in order from left to right. As soon as one is found to be true, the entire expression is known to be true. At that point, Python stops evaluating operands. The value of the entire expression is that of the x that terminates the evaluation.

To help demonstrate short-circuit evaluation, suppose that you have an identity function , f() , that behaves as follows:

  • Takes a single argument
  • Displays the function and its argument on the screen
  • Returns the argument as its return value

Here’s the code to define this function and also a few examples of how it works:

The f() function displays its argument, which visually confirms whether you called the function. It also returns the argument as you passed it in the call. Because of this behavior, you can make the expression f(arg) be truthy or falsy by specifying a value for arg that’s truthy or falsy, respectively.

Now, consider the following compound logical expression:

In this example, Python first evaluates f(0) , which returns 0 . This value is falsy. The expression isn’t true yet, so the evaluation continues from left to right. The next operand, f(False) , returns False . That value is also falsy, so the evaluation continues.

Next up is f(1) . That evaluates to 1 , which is truthy. At that point, Python stops the evaluation because it already knows that the entire expression is truthy. Consequently, Python returns 1 as the value of the expression and never evaluates the remaining operands, f(2) and f(3) . You can confirm from the output that the f(2) and f(3) calls don’t occur.

A similar behavior appears in an expression with multiple and operators like the following one:

This expression is truthy if all the operands are truthy. If at least one operand is falsy, then the expression is also falsy.

In this example, short-circuit evaluation dictates that Python stops evaluating as soon as an operand happens to be falsy. At that point, the entire expression is known to be false. Once that’s the case, Python stops evaluating operands and returns the falsy operand that terminated the evaluation.

Here are two examples that confirm the short-circuiting behavior:

In both examples, the evaluation stops at the first falsy term— f(False) in the first case, f(0.0) in the second case—and neither the f(2) nor the f(3) call occurs. In the end, the expressions return False and 0.0 , respectively.

If all the operands are truthy, then Python evaluates them all and returns the last (rightmost) one as the value of the expression:

In the first example, all the operands are truthy. The expression is also truthy and returns the last operand. In the second example, all the operands are truthy except for the last one. The expression is falsy and returns the last operand.

As you dig into Python, you’ll find that there are some common idiomatic patterns that exploit short-circuit evaluation for conciseness of expression, performance, and safety. For example, you can take advantage of this type of evaluation for:

  • Avoiding an exception
  • Providing a default value
  • Skipping a costly operation

To illustrate the first point, suppose you have two variables, a and b , and you want to know whether the division of b by a results in a number greater than 0 . In this case, you can run the following expression or condition:

This code works. However, you need to account for the possibility that a might be 0 , in which case you’ll get an exception :

In this example, the divisor is 0 , which makes Python raise a ZeroDivisionError exception. This exception breaks your code. You can skip this error with an expression like the following:

When a is 0 , a != 0 is false. Python’s short-circuit evaluation ensures that the evaluation stops at that point, which means that (b / a) never runs, and the error never occurs.

Using this technique, you can implement a function to determine whether an integer is divisible by another integer:

In this function, if b is 0 , then a / b isn’t defined. So, the numbers aren’t divisible. If b is different from 0 , then the result will depend on the remainder of the division.

Selecting a default value when a specified value is falsy is another idiom that takes advantage of the short-circuit evaluation feature of Python’s logical operators.

For example, say that you have a variable that’s supposed to contain a country’s name. At some point, this variable can end up holding an empty string. If that’s the case, then you’d like the variable to hold a default county name. You can also do this with the or operator:

If country is non-empty, then it’s truthy. In this scenario, the expression will return the first truthy value, which is country in the first or expression. The evaluation stops, and you get "Canada" as a result.

On the other hand, if country is an empty string , then it’s falsy. The evaluation continues to the next operand, default_country , which is truthy. Finally, you get the default country as a result.

Another interesting use case for short-circuit evaluation is to avoid costly operations while creating compound logical expressions. For example, if you have a costly operation that should only run if a given condition is false, then you can use or like in the following snippet:

In this construct, your clean_data() function represents a costly operation. Because of short-circuit evaluation, this function will only run when data_is_clean is false, which means that your data isn’t clean.

Another variation of this technique is when you want to run a costly operation if a given condition is true. In this case, you can use the and operator:

In this example, the and operator evaluates data_is_updated . If this variable is true, then the evaluation continues, and the process_data() function runs. Otherwise, the evaluation stops, and process_data() never runs.

Sometimes you have a compound expression that uses the and operator to join comparison expressions. For example, say that you want to determine if a number is in a given interval. You can solve this problem with a compound expression like the following:

In this example, you use the and operator to join two comparison expressions that allow you to find out if number is in the interval from 0 to 10 , both included.

In Python, you can make this compound expression more concise by chaining the comparison operators together. For example, the following chained expression is equivalent to the previous compound one:

This expression is more concise and readable than the original expression. You can quickly realize that this code is checking if the number is between 0 and 10 . Note that in most programming languages, this chained expression doesn’t make sense. In Python, it works like a charm.

In other programming languages, this expression would probably start by evaluating 0 <= number , which is true. This true value would then be compared with 10 , which doesn’t make much sense, so the expression fails.

Python internally processes this type of expression as an equivalent and expression, such as 0 <= number and number <= 10 . That’s why you get the correct result in the example above.

Python has what it calls conditional expressions . These kinds of expressions are inspired by the ternary operator that looks like a ? b : c and is used in other programming languages. This construct evaluates to b if the value of a is true, and otherwise evaluates to c . Because of this, sometimes the equivalent Python syntax is also known as the ternary operator.

However, in Python, the expression looks more readable:

This expression returns expression_1 if the condition is true and expression_2 otherwise. Note that this expression is equivalent to a regular conditional like the following:

So, why does Python need this syntax? PEP 308 introduced conditional expressions as an effort to avoid the prevalence of error-prone attempts to achieve the same effect of a traditional ternary operator using the and and or operators in an expression like the following:

However, this expression doesn’t work as expected, returning expression_2 when expression_1 is falsy.

Some Python developers would avoid the syntax of conditional expressions in favor of a regular conditional statement. In any case, this syntax can be handy in some situations because it provides a concise tool for writing two-way conditionals.

Here’s an example of how to use the conditional expression syntax in your code:

When day is equal to "Sunday" , the condition is true and you get the first expression, "11AM" , as a result. If the condition is false, then you get the second expression, "9AM" . Note that similarly to the and and or operators, the conditional expression returns the value of one of its expressions rather than a Boolean value.

Python provides two operators, is and is not , that allow you to determine whether two operands have the same identity . In other words, they let you check if the operands refer to the same object. Note that identity isn’t the same thing as equality. The latter aims to check whether two operands contain the same data.

Note: To learn more about the difference between identity and equality, check out Python ‘!=’ Is Not ‘is not’: Comparing Objects in Python .

Here’s a summary of Python’s identity operators. Note that x and y are variables that point to objects:

Operator Sample Expression Result
• if and hold a reference to the same in-memory object
• otherwise
• if points to an object different from the object that points to
• otherwise

These two Python operators are keywords instead of odd symbols. This is part of Python’s goal of favoring readability in its syntax.

Here’s an example of two variables, x and y , that refer to objects that are equal but not identical:

In this example, x and y refer to objects whose value is 1001 . So, they’re equal. However, they don’t reference the same object. That’s why the is operator returns False . You can check an object’s identity using the built-in id() function:

As you can conclude from the id() output, x and y don’t have the same identity. So, they’re different objects, and because of that, the expression x is y returns False . In other words, you get False because you have two different instances of 1001 stored in your computer’s memory.

When you make an assignment like y = x , Python creates a second reference to the same object. Again, you can confirm that with the id() function or the is operator:

In this example, a and b hold references to the same object, the string "Hello, Pythonista!" . Therefore, the id() function returns the same identity when you call it with a and b . Similarly, the is operator returns True .

Note: You should note that, on your computer, you’ll get a different identity number when you call id() in the example above. The key detail is that the identity number will be the same for a and b .

Finally, the is not operator is the opposite of is . So, you can use is not to determine if two names don’t refer to the same object:

In the first example, because x and y point to different objects in your computer’s memory, the is not operator returns True . In the second example, because a and b are references to the same object, the is not operator returns False .

Note: The syntax not x is y also works the same as x is not y . However, the former syntax looks odd and is difficult to read. That’s why Python recognizes is not as an operator and encourages its use for readability.

Again, the is not operator highlights Python’s readability goals. In general, both identity operators allow you to write checks that read as plain English.

Sometimes you need to determine whether a value is present in a container data type, such as a list, tuple, or set. In other words, you may need to check if a given value is or is not a member of a collection of values. Python calls this kind of check a membership test .

Note: For a deep dive into how Python’s membership tests work, check out Python’s “in” and “not in” Operators: Check for Membership .

Membership tests are quite common and useful in programming. As with many other common operations, Python has dedicated operators for membership tests. The table below lists the membership operators in Python:

Operator Sample Expression Result
• if present in
• otherwise
• if present in of values
• otherwise

As usual, Python favors readability by using English words as operators instead of potentially confusing symbols or combinations of symbols.

Note: The syntax not value in collection also works in Python. However, this syntax looks odd and is difficult to read. So, to keep your code clean and readable, you should use value not in collection , which almost reads as plain English.

The Python in and not in operators are binary. This means that you can create membership expressions by connecting two operands with either operator. However, the operands in a membership expression have particular characteristics:

  • Left operand : The value that you want to look for in a collection of values
  • Right operand : The collection of values where the target value may be found

To better understand the in operator, below you have two demonstrative examples consisting of determining whether a value is in a list:

The first expression returns True because 5 is in the list of numbers. The second expression returns False because 8 isn’t in the list.

The not in membership operator runs the opposite test as the in operator. It allows you to check whether an integer value is not in a collection of values:

In the first example, you get False because 5 is in the target list. In the second example, you get True because 8 isn’t in the list of values. This may sound like a tongue twister because of the negative logic. To avoid confusion, remember that you’re trying to determine if the value is not part of a given collection of values.

There are two operators in Python that acquire a slightly different meaning when you use them with sequence data types, such as lists, tuples, and strings. With these types of operands, the + operator defines a concatenation operator , and the * operator represents the repetition operator :

Operator Operation Sample Expression Result
Concatenation A new sequence containing all the items from both operands
Repetition A new sequence containing the items of repeated times

Both operators are binary. The concatenation operator takes two sequences as operands and returns a new sequence of the same type. The repetition operator takes a sequence and an integer number as operands. Like in regular multiplication, the order of the operands doesn’t alter the repetition’s result.

Note: To learn more about concatenating string objects, check out Efficient String Concatenation in Python .

Here are some examples of how the concatenation operator works in practice:

In the first example, you use the concatenation operator ( + ) to join two strings together. The operator returns a completely new string object that combines the two original strings.

In the second example, you concatenate two tuples of letters together. Again, the operator returns a new tuple object containing all the items from the original operands. In the final example, you do something similar but this time with two lists.

Note: To learn more about concatenating lists, check out the Concatenating Lists section in the tutorial Python’s list Data Type: A Deep Dive With Examples .

When it comes to the repetition operator, the idea is to repeat the content of a given sequence a certain number of times. Here are a few examples:

In the first example, you use the repetition operator ( * ) to repeat the "Hello" string three times. In the second example, you change the order of the operands by placing the integer number on the left and the target string on the right. This example shows that the order of the operands doesn’t affect the result.

The next examples use the repetition operators with a tuple and a list, respectively. In both cases, you get a new object of the same type containing the items in the original sequence repeated three times.

Regular assignment statements with the = operator don’t have a return value, as you already learned. Instead, the assignment operator creates or updates variables. Because of this, the operator can’t be part of an expression.

Since Python 3.8 , you have access to a new operator that allows for a new type of assignment. This new assignment is called assignment expression or named expression . The new operator is called the walrus operator , and it’s the combination of a colon and an equal sign ( := ).

Note: The name walrus comes from the fact that this operator resembles the eyes and tusks of a walrus lying on its side. For a deep dive into how this operator works, check out The Walrus Operator: Python’s Assignment Expressions .

Unlike regular assignments, assignment expressions do have a return value, which is why they’re expressions . So, the operator accomplishes two tasks:

  • Returns the expression’s result
  • Assigns the result to a variable

The walrus operator is also a binary operator. Its left-hand operand must be a variable name, and its right-hand operand can be any Python expression. The operator will evaluate the expression, assign its value to the target variable, and return the value.

The general syntax of an assignment expression is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, in certain situations, you won’t need them. Either way, they won’t hurt you, so it’s safe to use them.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand. It’s particularly useful in the context of a conditional statement. To illustrate, the example below shows a toy function that checks the length of a string object:

In this example, you use a conditional statement to check whether the input string has fewer than 8 characters.

The assignment expression, (n := len(string)) , computes the string length and assigns it to n . Then it returns the value that results from calling len() , which finally gets compared with 8 . This way, you guarantee that you have a reference to the string length to use in further operations.

Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. Currently, Python supports the following bitwise operators:

Operator Operation Sample Expression Result
Bitwise AND • Each bit position in the result is the logical AND of the bits in the corresponding position of the operands.
• if both bits are , otherwise .
Bitwise OR • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if either bit is , otherwise .
Bitwise NOT • Each bit position in the result is the logical negation of the bit in the corresponding position of the operand.
• if the bit is and if the bit is .
Bitwise XOR (exclusive OR) • Each bit position in the result is the logical of the bits in the corresponding position of the operands.
• if the bits in the operands are different, if they’re equal.
Bitwise right shift Each bit is shifted right places.
Bitwise left shift Each bit is shifted left places.

As you can see in this table, most bitwise operators are binary, which means that they expect two operands. The bitwise NOT operator ( ~ ) is the only unary operator because it expects a single operand, which should always appear at the right side of the expression.

You can use Python’s bitwise operators to manipulate your data at its most granular level, the bits. These operators are commonly useful when you want to write low-level algorithms, such as compression, encryption, and others.

Note: For a deep dive into the bitwise operators, check out Bitwise Operators in Python . You can also check out Build a Maze Solver in Python Using Graphs for an example of using bitwise operators to construct a binary file format.

Here are some examples that illustrate how some of the bitwise operators work in practice:

In the first example, you use the bitwise AND operator. The commented lines begin with # and provide a visual representation of what happens at the bit level. Note how each bit in the result is the logical AND of the bits in the corresponding position of the operands.

The second example shows how the bitwise OR operator works. In this case, the resulting bits are the logical OR test of the corresponding bits in the operands.

In all the examples, you’ve used the built-in bin() function to display the result as a binary object. If you don’t wrap the expression in a call to bin() , then you’ll get the integer representation of the output.

Up to this point, you’ve coded sample expressions that mostly use one or two different types of operators. However, what if you need to create compound expressions that use several different types of operators, such as comparison, arithmetic, Boolean, and others? How does Python decide which operation runs first?

Consider the following math expression:

There might be ambiguity in this expression. Should Python perform the addition 20 + 4 first and then multiply the result by 10 ? Should Python run the multiplication 4 * 10 first, and the addition second?

Because the result is 60 , you can conclude that Python has chosen the latter approach. If it had chosen the former, then the result would be 240 . This follows a standard algebraic rule that you’ll find in virtually all programming languages.

All operators that Python supports have a precedence compared to other operators. This precedence defines the order in which Python runs the operators in a compound expression.

In an expression, Python runs the operators of highest precedence first. After obtaining those results, Python runs the operators of the next highest precedence. This process continues until the expression is fully evaluated. Any operators of equal precedence are performed in left-to-right order.

Here’s the order of precedence of the Python operators that you’ve seen so far, from highest to lowest:

Operators Description
Exponentiation
, , Unary positive, unary negation, bitwise negation
, , , Multiplication, division, floor division,
, Addition, subtraction
, Bitwise shifts
Bitwise AND
Bitwise XOR
Bitwise OR
, , , , , , , , , Comparisons, identity, and membership
Boolean NOT
Boolean AND
Boolean OR
Walrus

Operators at the top of the table have the highest precedence, and those at the bottom of the table have the lowest precedence. Any operators in the same row of the table have equal precedence.

Getting back to your initial example, Python runs the multiplication because the multiplication operator has a higher precedence than the addition one.

Here’s another illustrative example:

In the example above, Python first raises 3 to the power of 4 , which equals 81 . Then, it carries out the multiplications in order from left to right: 2 * 81 = 162 and 162 * 5 = 810 .

You can override the default operator precedence using parentheses to group terms as you do in math. The subexpressions in parentheses will run before expressions that aren’t in parentheses.

Here are some examples that show how a pair of parentheses can affect the result of an expression:

In the first example, Python computes the expression 20 + 4 first because it’s wrapped in parentheses. Then Python multiplies the result by 10 , and the expression returns 240 . This result is completely different from what you got at the beginning of this section.

In the second example, Python evaluates 4 * 5 first. Then it raises 3 to the power of the resulting value. Finally, Python multiplies the result by 2 , returning 6973568802 .

There’s nothing wrong with making liberal use of parentheses, even when they aren’t necessary to change the order of evaluation. Sometimes it’s a good practice to use parentheses because they can improve your code’s readability and relieve the reader from having to recall operator precedence from memory.

Consider the following example:

Here the parentheses are unnecessary, as the comparison operators have higher precedence than and . However, some might find the parenthesized version clearer than the version without parentheses:

On the other hand, some developers might prefer this latter version of the expression. It’s a matter of personal preference. The point is that you can always use parentheses if you feel that they make your code more readable, even if they aren’t necessary to change the order of evaluation.

So far, you’ve learned that a single equal sign ( = ) represents the assignment operator and allows you to assign a value to a variable. Having a right-hand operand that contains other variables is perfectly valid, as you’ve also learned. In particular, the expression to the right of the assignment operator can include the same variable that’s on the left of the operand.

That last sentence may sound confusing, so here’s an example that clarifies the point:

In this example, total is an accumulator variable that you use to accumulate successive values. You should read this example as total is equal to the current value of total plus 5 . This expression effectively increases the value of total , which is now 15 .

Note that this type of assignment only makes sense if the variable in question already has a value. If you try the assignment with an undefined variable, then you get an error:

In this example, the count variable isn’t defined before the assignment, so it doesn’t have a current value. In consequence, Python raises a NameError exception to let you know about the issue.

This type of assignment helps you create accumulators and counter variables, for example. Therefore, it’s quite a common task in programming. As in many similar cases, Python offers a more convenient solution. It supports a shorthand syntax called augmented assignment :

In the highlighted line, you use the augmented addition operator ( += ). With this operator, you create an assignment that’s fully equivalent to total = total + 5 .

Python supports many augmented assignment operators. In general, the syntax for this type of assignment looks something like this:

Note that the dollar sign ( $ ) isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. The above statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the assignment operator ( = ), using the current value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

The table below shows a summary of the augmented operators for arithmetic operations:

Operator Description Sample Expression Equivalent Expression
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

As you can conclude from this table, all the arithmetic operators have an augmented version in Python. You can use these augmented operators as a shortcut when creating accumulators, counters, and similar objects.

Did the augmented arithmetic operators look neat and useful to you? The good news is that there are more. You also have augmented bitwise operators in Python:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

Finally, the concatenation and repetition operators have augmented variations too. These variations behave differently with mutable and immutable data types:

Operator Description Example
• Runs an augmented concatenation operation on the target sequence.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.
• Adds to itself times.
• Mutable sequences are updated in place.
• If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator works on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Now you know what operators Python supports and how to use them. Operators are symbols, combinations of symbols, or keywords that you can use along with Python objects to build different types of expressions and perform computations in your code.

In this tutorial, you’ve learned:

  • What Python’s arithmetic operators are and how to use them in arithmetic expressions
  • What Python’s comparison , Boolean , identity , membership operators are
  • How to write expressions using comparison, Boolean, identity, and membership operators
  • Which bitwise operators Python supports and how to use them
  • How to combine and repeat sequences using the concatenation and repetition operators
  • What the augmented assignment operators are and how they work

In other words, you’ve covered an awful lot of ground! If you’d like a handy cheat sheet that can jog your memory on all that you’ve learned, then click the link below:

With all this knowledge about operators, you’re better prepared as a Python developer. You’ll be able to write better and more robust expressions in your code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Dan Bader

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Operators and Expressions in Python (Cheat Sheet)

🔒 No spam. We take your privacy seriously.

assignment 4 python

  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Augmented Assignment Operators in Python

An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write “ a = 5 “ to assign value 5 to variable ‘a’. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator. So assume if we need to add 7 to a variable “a” and assign the result back to “a”, then instead of writing normally as “ a = a + 7 “, we can use the augmented assignment operator and write the expression as “ a += 7 “. Here += has combined the functionality of arithmetic addition and assignment.

So, augmented assignment operators provide a short way to perform a binary operation and assigning results back to one of the operands. The way to write an augmented operator is just to write that binary operator and assignment operator together. In Python, we have several different augmented assignment operators like +=, -=, *=, /=, //=, **=, |=, &=, >>=, <<=, %= and ^=. Let’s see their functioning with the help of some exemplar codes:

1. Addition and Assignment (+=): This operator combines the impact of arithmetic addition and assignment. Here,

 a = a + b can be written as a += b

2. Subtraction and Assignment (-=): This operator combines the impact of subtraction and assignment.  

a = a – b can be written as a -= b

Example:  

3. Multiplication and Assignment (*=): This operator combines the functionality of multiplication and assignment.  

a = a * b can be written as a *= b

4. Division and Assignment (/=): This operator has the combined functionality of division and assignment.  

a = a / b can be written as a /= b

5. Floor Division and Assignment (//=): It performs the functioning of floor division and assignment.  

a = a // b can be written as a //= b

6. Modulo and Assignment (%=): This operator combines the impact of the modulo operator and assignment.  

a = a % b can be written as a %= b

7. Power and Assignment (**=): This operator is equivalent to the power and assignment operator together.  

a = a**b can be written as a **= b

8. Bitwise AND & Assignment (&=): This operator combines the impact of the bitwise AND operator and assignment operator. 

a = a & b can be written as a &= b

9. Bitwise OR and Assignment (|=): This operator combines the impact of Bitwise OR and assignment operator.  

a = a | b can be written as a |= b

10. Bitwise XOR and Assignment (^=): This augmented assignment operator combines the functionality of the bitwise XOR operator and assignment operator. 

a = a ^ b can be written as a ^= b

11. Bitwise Left Shift and Assignment (<<=): It puts together the functioning of the bitwise left shift operator and assignment operator.  

a = a << b can be written as a <<= b

12. Bitwise Right Shift and Assignment (>>=): It puts together the functioning of the bitwise right shift operator and assignment operator.  

a = a >> b can be written as a >>= b

Please Login to comment...

Similar reads.

  • School Learning
  • School Programming
  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • 10 Best Free VPN Services in 2024

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Assignment 1

    assignment 4 python

  2. Python assignment:

    assignment 4 python

  3. Python Assignment Expression? The 13 Top Answers

    assignment 4 python

  4. 22MCA2008 4 python assignment 1

    assignment 4 python

  5. Multiple Of 3 In Python

    assignment 4 python

  6. SOLUTION: Python code assignment 4

    assignment 4 python

VIDEO

  1. Introduction to internet of things nptel week 4 assignment answers || Learn in brief

  2. Python for everybody: data structures assignment 8.4

  3. Python Week 5 Graded Assignment // IITM BS Online Degree Program || Foundation #python #gasolution

  4. NPTEL Programming, Data Structures and Algorithms using Python Assignment 4 Answers Week 4 July 2024

  5. Data Analytics with Python Week 4 Assignment Solutions 2024 || @OPEducore

  6. Python Multiple Assignment

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

    In this tutorial, you'll learn how to use Python's assignment operators to write assignment statements that allow you to create, initialize, and update variables in your code.

  2. Python Assignment Operators - W3Schools

    Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.

  3. Assignment Operators in Python - GeeksforGeeks

    Assignment operators in Python are used to assign values to variables. These operators can also perform additional operations during the assignment. The basic assignment operator is =, which simply assigns the value of the right-hand operand to the left-hand operand.

  4. Different Forms of Assignment Statements in Python

    Different Forms of Assignment Statements in Python. We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object.

  5. Python Assignment Operators - Educative

    Code. Assignment Operators. For demonstration purposes, let’s use a single variable, num. Initially, we set num to 6. We can apply all of these operators to num and update it accordingly. Assignment. Assigning the value of 6 to num results in num being 6. Expression: num = 6. Add and assign.

  6. python - What are assignment expressions (using the "walrus ...

    In simple terms := is a expression + assignment operator. it executes an expression and assigns the result of that expression in a single variable. Why is := operator needed? simple useful case will be to reduce function calls in comprehensions while maintaining the redability.

  7. How To Use Assignment Expressions in Python - DigitalOcean

    In this tutorial, you used assignment expressions to make compact sections of Python code that assign values to variables inside of if statements, while loops, and list comprehensions. For more information on other assignment expressions, you can view PEP 572—the document that initially proposed adding assignment expressions to Python.

  8. Python - Assignment Operators - Online Tutorials Library

    Python Assignment Operator. The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left.

  9. Operators and Expressions in Python

    The assignment operator is one of the most frequently used operators in Python. The operator consists of a single equal sign ( = ), and it operates on two operands. The left-hand operand is typically a variable , while the right-hand operand is an expression.

  10. Augmented Assignment Operators in Python - GeeksforGeeks

    In Python, we have several different augmented assignment operators like +=, -=, *=, /=, //=, **=, |=, &=, >>=, <<=, %= and ^=. Let’s see their functioning with the help of some exemplar codes: 1. Addition and Assignment (+=): This operator combines the impact of arithmetic addition and assignment. Here,