Python Simplified Assignment Operators

CK CK 3776 
Created at  
533 0 0

Python also supports various simplified (or compound) assignment operators. These operators work similarly to those in PHP, combining an operation with an assignment to make the code more concise.

1. Arithmetic Assignment Operators

These operators perform arithmetic and assignment together.

  • Addition: a += b is equivalent to a = a + b
  • Subtraction: a -= b is equivalent to a = a - b
  • Multiplication: a *= b is equivalent to a = a * b
  • Division: a /= b is equivalent to a = a / b
  • Floor Division: a //= b is equivalent to a = a // b
  • Modulus: a %= b is equivalent to a = a % b
  • Exponentiation: a **= b is equivalent to a = a ** b

 

2. Bitwise Assignment Operators

These operators apply bitwise operations and assignment in one step.

  • Bitwise AND: a &= b is equivalent to a = a & b
  • Bitwise OR: a |= b is equivalent to a = a | b
  • Bitwise XOR: a ^= b is equivalent to a = a ^ b
  • Left Shift: a <<= b is equivalent to a = a << b
  • Right Shift: a >>= b is equivalent to a = a >> b

 

3. Logical Assignment Operators

Python doesn’t have explicit logical assignment operators like JavaScript, but logical operations can be combined with assignment using idioms such as conditional expressions.

 

 

4. Walrus Operator (Python 3.8+)

The walrus operator := assigns a value to a variable as part of an expression. It is helpful in conditional statements and loop structures.

Example:

if (n := len(some_list)) > 5:
    print(f"List has {n} elements.")

Example Usage in Python

x = 10
x += 5   # x is now 15

y = 20
y //= 3  # y is now 6 (integer division)

z = 2
z **= 3  # z is now 8 (2^3)

a = 5
a |= 3   # a is now 7 (bitwise OR)

some_list = [1, 2, 3, 4, 5]
if (n := len(some_list)) > 4:
    print(f"The list has {n} elements.")

These simplified operators help streamline code in Python, making it easier to read and more efficient.

Tags Bitwise Operators Logical Assignment Operators Python Assignment Operators Python Simplified Assignment Operators Walrus Operator Facebook X
Comments 0
Similar posts
  1. PHP Simplified Operators
    317
  1. CUDA versus OpenCL
    575
  2. Simple gRPC server based on Python
    392
  3. Python code to convert PDF file to Excel Spreadsheet
    692
  4. Python script to list files on your Google Drive and download one of them
    938
  5. Coinbase Python API - Basic Example
    461
  6. AWS Lambda Code Example based on Python
    333
  7. Python code using GPU on CentOS with AWS
    1,247
  8. Video Scence Detection with PySceneDetect
    2,318
  9. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,430
  10. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    900
  11. Deleting a specific user voice from the original audio track with Python
    546
  12. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    436
  13. Creating mp3 audio file based on the text input with Python
    461
  14. Implementing Text To Speech / Audio with Python3 and pyttsx3
    353
  15. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    558
  16. Trackback module used for Python Threading debugging
    839
  17. Python Flask with simple HTML files to server web pages along with API
    926
  18. Python Flask web server tutorial from the scratch
    618
  19. Simple Web Server based in Python
    366
  20. Thread Implementation in Python
    506
  21. A shell script that activates a Python virtual environment and then runs a specific Python script
    740
  22. Learning about Python Multiprocessing Technique
    590
  23. Simple Example to get the total number of records in BigQuery with Python
    665
  24. Using BigQuery in Python
    407
  25. Python Web Programming based on Django from the Scratch
    366
  26. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    183
  27. How do I determine the client IP type in Python - IPv4 or IPv6
    758
  28. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,228
  29. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  30. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,067
Recently updated
  1. How do I create animated background for Google Meet?
    19,000
  2. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    192
  3. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    75
  4. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    151
  5. Array of arguments passed to script in PHP
    83
  6. Invalid Auction Storms in Ad Tech
    91
  7. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    194
  8. The Two Clocks of Ad Server Architecture
    61
  9. Frequency Cap Architecture Overview
    505
  10. Collecting Proof-of-Play from 100,000 Screens
    139
  11. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    276
  12. What is RedisVL?
    102
  13. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    218
  14. TPU & GPU Cluster Management Tools
    229
  15. The Concept of Scaffolding in AI Agents
    217
  16. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    568
  17. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    246
  18. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    321
  19. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    196
  20. Machine Learning: Training vs. Ranking
    200
  21. The Continuous Learning Machine: Designing a Loop That Actually Turns
    212
  22. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    188
  23. Designing a Data Curation System Around a Vector Database
    212
  24. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    228
  25. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    646
  26. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    180
  27. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    203
  28. Understanding Data Lineage
    251
  29. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    159
  30. GPU & LLM Cluster Infrastructure & Task Scheduling Architecture
    229