TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Operator Precedence in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Operator Precedence in Python

Last updated: Sep 25, 2023 1:00 am
By Meenakshi Agarwal
Share
6 Min Read
Python Operator Precedence and Associativity
Python Operator Precedence and Associativity
SHARE

In this tutorial, you’ll learn about Python operator precedence and associativity. This topic is crucial for programmers to understand the semantics of Python operators. After reading it, you should be able to know how Python evaluates the order of its operators.

Contents
How does the operator precedence work in Python?Examples of operator precedence in PythonOperator precedence table in PythonWhat does associativity mean in Python?Examples of associativity in PythonExamples of nonassociative operators

Python Operator Precedence and Associativity

Some operators in Python have higher precedence than others such as the multiplication operator has higher priority than the addition operator, so do multiplication before addition.

Python Operator Precedence and Associativity
Python Operator Precedence and Associativity

Python operator precedence

In an expression, the Python interpreter evaluates operators with higher precedence first. And, except the exponent operator (**) all other operators get evaluated from left to right.

How does the operator precedence work in Python?

When we group a set of values, variables, operators or function calls that turn out as an expression. And once you execute that expression, the Python interpreter evaluates it as a valid expression. See a simple example given below.

>>> 3 + 4
7

Here, the ‘3 +4’ is a Python statement. It contains one operator and two operands. However, a more complex statement can include multiple operators.

To evaluate complex expressions, Python lays out the rule of precedence. It governs the order in which the operations take place.

Examples of operator precedence in Python

See the below example which combines multiple operators to form a compound expression.

# Multiplication get evaluated before
# the addition operation
# Result: 17
5 + 4 * 3

However, it is possible to alter the evaluation order with the help of parentheses (). It can override the precedence of the arithmetic operators.

# Parentheses () overriding the precedence of the arithmetic operators
# Output: 27
(5 + 4) * 3

Operator precedence table in Python

Refer to the below table which lists the operators with the highest precedence at the top and lowest at the bottom.

OperatorsUsage
{ }Parentheses (grouping)
f(args…)Function call
x[index:index]Slicing
x[index]Subscription
x.attributeAttribute reference
**Exponent
~xBitwise not
+x, -xPositive, negative
*, /, %Product, division, remainder
+, –Addition, subtraction
<<, >>Shifts left/right
&Bitwise AND
^Bitwise XOR
|Bitwise OR
in, not in, is, is not, <, <=, >, >=,
<>, !=, ==
Comparisons, membership, identity
not xBoolean NOT
andBoolean AND
orBoolean OR
lambdaLambda expression

Python operator associativity

In the above table, you can confirm that some of the groups have many operators. It means that all operators in a group are at the same precedence level.

And, whenever two or more operators have the same precedence, then associativity defines the order of operations.

What does associativity mean in Python?

The associativity is the order in which Python evaluates an expression containing multiple operators of the same precedence. Almost all operators except the exponent (**) support the left-to-right associativity.

Examples of associativity in Python

For example, the product (*) and the modulus (%) have the same precedence. So, if both appear in an expression, then the left one will get evaluated first.

# Testing Left-right associativity
# Result: 1
print(4 * 7 % 3)

# Testing left-right associativity
# Result: 0
print(2 * (10 % 5))

As said earlier, the only operator that has right-to-left associativity in Python is the exponent (**) operator. See the examples below.

# Checking right-left associativity of ** exponent operator
# Output: 256
print(4 ** 2 ** 2)

# Checking the right-left associativity
# of **
# Output: 256
print((4 ** 2) ** 2)

You might have observed that the ‘print(4 ** 2 ** 2)’ is similar to ‘(4 ** 2 ** 2).

Nonassociative operators in Python

Python does have some operators such as assignment operators and comparison operators which don’t support associativity. Instead, there are special rules for the ordering of this type of operator which can’t be managed via associativity.

Examples of nonassociative operators

For example, the expression 5 < 7 < 9 does not mean (5 < 7) < 9 or 5 < (7 < 9). Also, the statement 5 < 7 < 9 is the same as 5 < 7 and 7 < 9 and gets evaluated from left to right.

Moreover, chaining of assignment operators like a = b = c is perfectly alright whereas the ‘a = b += c’ will result in an error.

# Set the values of a, b, c
x = 11, y = 12, z = 13

# Expression is incorrect
# Non-associative operators
# Error -> SyntaxError: invalid syntax

x = y += 12

Now, you might also like to check out the most versatile XOR operator in Python. It can come in handy in many of your programming tasks.

Conclusion – Python operator precedence

This tutorial did cover a very important topic – Python operator precedence and associativity. So, it should now be easier for you to create compound/complex expressions in Python.

If you find something new to learn today, then do share it with others. And, follow us on our social media accounts to get the latest tutorials and updates.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Operators Tutorial for Beginners to Learn Python Operators – A Practical Guide for Beginners
Next Article Python Namespace, Scope, and Scope Resolution Python Namespace Explained

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x