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:

Related Pages

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

  • Python »
  • 3.12.2 Documentation »
  • The Python Standard Library »
  • Functional Programming Modules »
  • operator — Standard operators as functions
  • Theme Auto Light Dark |

operator — Standard operators as functions ¶

Source code: Lib/operator.py

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y . Many function names are those used for special methods, without the double underscores. For backward compatibility, many of these have a variant with the double underscores kept. The variants without the double underscores are preferred for clarity.

The functions fall into categories that perform object comparisons, logical operations, mathematical operations and sequence operations.

The object comparison functions are useful for all objects, and are named after the rich comparison operators they support:

Perform “rich comparisons” between a and b . Specifically, lt(a, b) is equivalent to a < b , le(a, b) is equivalent to a <= b , eq(a, b) is equivalent to a == b , ne(a, b) is equivalent to a != b , gt(a, b) is equivalent to a > b and ge(a, b) is equivalent to a >= b . Note that these functions can return any value, which may or may not be interpretable as a Boolean value. See Comparisons for more information about rich comparisons.

The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations:

Return the outcome of not obj . (Note that there is no __not__() method for object instances; only the interpreter core defines this operation. The result is affected by the __bool__() and __len__() methods.)

Return True if obj is true, and False otherwise. This is equivalent to using the bool constructor.

Return a is b . Tests object identity.

Return a is not b . Tests object identity.

The mathematical and bitwise operations are the most numerous:

Return the absolute value of obj .

Return a + b , for a and b numbers.

Return the bitwise and of a and b .

Return a // b .

Return a converted to an integer. Equivalent to a.__index__() .

Changed in version 3.10: The result always has exact type int . Previously, the result could have been an instance of a subclass of int .

Return the bitwise inverse of the number obj . This is equivalent to ~obj .

Return a shifted left by b .

Return a % b .

Return a * b , for a and b numbers.

Return a @ b .

New in version 3.5.

Return obj negated ( -obj ).

Return the bitwise or of a and b .

Return obj positive ( +obj ).

Return a ** b , for a and b numbers.

Return a shifted right by b .

Return a - b .

Return a / b where 2/3 is .66 rather than 0. This is also known as “true” division.

Return the bitwise exclusive or of a and b .

Operations which work with sequences (some of them with mappings too) include:

Return a + b for a and b sequences.

Return the outcome of the test b in a . Note the reversed operands.

Return the number of occurrences of b in a .

Remove the value of a at index b .

Return the value of a at index b .

Return the index of the first of occurrence of b in a .

Set the value of a at index b to c .

Return an estimated length for the object obj . First try to return its actual length, then an estimate using object.__length_hint__() , and finally return the default value.

New in version 3.4.

The following operation works with callables:

Return obj(*args, **kwargs) .

New in version 3.11.

The operator module also defines tools for generalized attribute and item lookups. These are useful for making fast field extractors as arguments for map() , sorted() , itertools.groupby() , or other functions that expect a function argument.

Return a callable object that fetches attr from its operand. If more than one attribute is requested, returns a tuple of attributes. The attribute names can also contain dots. For example:

After f = attrgetter('name') , the call f(b) returns b.name .

After f = attrgetter('name', 'date') , the call f(b) returns (b.name, b.date) .

After f = attrgetter('name.first', 'name.last') , the call f(b) returns (b.name.first, b.name.last) .

Equivalent to:

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example:

After f = itemgetter(2) , the call f(r) returns r[2] .

After g = itemgetter(2, 5, 3) , the call g(r) returns (r[2], r[5], r[3]) .

The items can be any type accepted by the operand’s __getitem__() method. Dictionaries accept any hashable value. Lists, tuples, and strings accept an index or a slice:

Example of using itemgetter() to retrieve specific fields from a tuple record:

Return a callable object that calls the method name on its operand. If additional arguments and/or keyword arguments are given, they will be given to the method as well. For example:

After f = methodcaller('name') , the call f(b) returns b.name() .

After f = methodcaller('name', 'foo', bar=1) , the call f(b) returns b.name('foo', bar=1) .

Mapping Operators to Functions ¶

This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the operator module.

In-place Operators ¶

Many operations have an “in-place” version. Listed below are functions providing a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x = operator.iadd(x, y) . Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y .

In those examples, note that when an in-place method is called, the computation and assignment are performed in two separate steps. The in-place functions listed below only do the first step, calling the in-place method. The second step, assignment, is not handled.

For immutable targets such as strings, numbers, and tuples, the updated value is computed, but not assigned back to the input variable:

For mutable targets such as lists and dictionaries, the in-place method will perform the update, so no subsequent assignment is necessary:

a = iadd(a, b) is equivalent to a += b .

a = iand(a, b) is equivalent to a &= b .

a = iconcat(a, b) is equivalent to a += b for a and b sequences.

a = ifloordiv(a, b) is equivalent to a //= b .

a = ilshift(a, b) is equivalent to a <<= b .

a = imod(a, b) is equivalent to a %= b .

a = imul(a, b) is equivalent to a *= b .

a = imatmul(a, b) is equivalent to a @= b .

a = ior(a, b) is equivalent to a |= b .

a = ipow(a, b) is equivalent to a **= b .

a = irshift(a, b) is equivalent to a >>= b .

a = isub(a, b) is equivalent to a -= b .

a = itruediv(a, b) is equivalent to a /= b .

a = ixor(a, b) is equivalent to a ^= b .

Table of Contents

  • Mapping Operators to Functions
  • In-place Operators

Previous topic

functools — Higher-order functions and operations on callable objects

File and Directory Access

  • Report a Bug
  • Show Source

logo

Python Assignment Operators

In Python, an assignment operator is used to assign a value to a variable. The assignment operator is a single equals sign (=). Here is an example of using the assignment operator to assign a value to a variable:

In this example, the variable x is assigned the value 5.

There are also several compound assignment operators in Python, which are used to perform an operation and assign the result to a variable in a single step. These operators include:

  • +=: adds the right operand to the left operand and assigns the result to the left operand
  • -=: subtracts the right operand from the left operand and assigns the result to the left operand
  • *=: multiplies the left operand by the right operand and assigns the result to the left operand
  • /=: divides the left operand by the right operand and assigns the result to the left operand
  • %=: calculates the remainder of the left operand divided by the right operand and assigns the result to the left operand
  • //=: divides the left operand by the right operand and assigns the result as an integer to the left operand
  • **=: raises the left operand to the power of the right operand and assigns the result to the left operand

Here are some examples of using compound assignment operators:

Python In-Place Assignment Operators

In-place assignment operators (also called compound assignment operators) perform an operation in-place on a variable provided as first operand. They overwrite the value of the first operand variable with the result of the operation when performing the operator without assignment. For example, x += 3 is the same as x = x + 3 of first calculating the result of x + 3 and then assigning it to the variable x.

You can watch me go over all of these operators in the following video:

[Overview] Python&#039;s In-Place Assignment Operators | Compound Operators

We’ll rush over all in-place operators one-by-one next!

Python In-Place Addition

Python provides the operator x += y to add two objects in-place by calculating the sum x + y and assigning the result to the first operands variable name x . You can set up the in-place addition behavior for your own class by overriding the magic “dunder” method __iadd__(self, other) in your class definition.

The expression x += y is syntactical sugar for the longer-form x = x + y :

Related Tutorial: Python In-Place Addition

Python In-Place Subtraction

Python provides the operator x -= y to subtract two objects in-place by calculating the difference x - y and assigning the result to the first operands variable name x . You can set up the in-place subtraction behavior for your own class by overriding the magic “dunder” method __isub__(self, other) in your class definition.

The expression x -= y is syntactical sugar for the longer-form x = x - y :

Related Tutorial: Python In-Place Subtraction

Python In-Place Multiplication

Python provides the operator x *= y to multiply two objects in-place by calculating the product x * y and assigning the result to the first operands variable name x . You can set up the in-place multiplication behavior for your own class by overriding the magic “dunder” method __imul__(self, other) in your class definition.

The expression x *= y is syntactical sugar for the longer-form x = x * y :

Related Tutorial: Python In-Place Multiplication

Python In-Place Division

Python’s in-place division operator x /= y divides two objects in-place by calculating x / y and assigning the result to the first operands variable name x . Set up in-place division for your own class by overriding the magic “dunder” method __truediv__(self, other) in your class definition.

The expression x /= y is syntactical sugar for the longer-form x = x / y :

Related Tutorial: Python In-Place Division

Python In-Place Modulo

Python provides the operator x %= y to calculate the modulo operation x % y , and assign the result in-place to the first operands variable x . You can set up the in-place modulo behavior for your own class by overriding the magic “dunder” method __imod__(self, other) in your class definition.

The expression x %= y is syntactical sugar for the longer-form x = x % y :

Related Tutorial: Python In-Place Modulo

Python In-Place Integer Division

Python’s in-place integer division operator x //= y divides two objects in-place by calculating x // y and assigning the result to the first operands variable name x . Set up in-place integer (or floor) division for your own class by overriding the magic “dunder” method __floordiv__(self, other) in your class definition.

Related Tutorial: Python In-Place Integer Division

Python In-Place Exponentiation

Python provides the in-place exponentiation operator x **= y that raises x to the power of y using x ** y and assigns the result to the first operands variable name x . You can set up the in-place exponentiation behavior for your own class by overriding the magic “dunder” method __ipow__(self, other) in your class definition.

The expression x **= y is syntactical sugar for the longer-form x = x ** y :

Related Tutorial: Python In-Place Exponentiation

Python In-Place Bitwise AND

Python’s in-place bitwise AND operator x &= y calcualtes bitwise-and x & y and assigns the result to the first operand x . To set it up for your own class, override the magic “dunder” method __iand__(self, other) in your class definition.

The expression x &= y is syntactical sugar for the longer-form x = x & y :

Related Tutorial: Python In-Place Bitwise AND

Python In-Place Bitwise OR

Python’s A |= B applies the | operator in place. Thus, it is semantically identical to the longer-form version A = A | B of first performing the operation A | B and then assigning the result to the variable A .

The following minimal example creates two Boolean variables A and B and performs the in-place B |= A operation to perform a logical OR operation B | A and assigning the result to the first operand B that becomes True :

In this example, you’ve seen this in-place operation on Boolean operands. But the | operator is overloaded in Python. The three most frequent use cases for the | and |= operators are the following:

  • Python Sets : set union operator
  • Python Dictionaries : dictionary update operator
  • Python Booleans : logical OR operator

Related Tutorial: Python In-Place Bitwise OR

Python In-Place Bitwise XOR

Python’s in-place bitwise XOR operator x ^= y calcualtes bitwise XOR x ^ y and assigns the result to the first operand x . To set this up for your own class, override the magic “dunder” method __ixor__(self, other) in your class definition.

The expression x ^ = y is syntactical sugar for the longer-form x = x ^ y :

Related Tutorial: Python In-Place Bitwise XOR

Python In-Place Bitwise Right-Shift

Python’s in-place bitwise right-shift operator x >>= y calculates the right-shift operation x >> y , and assigns the result to the first operands variable name x . You can set up the in-place right-shift behavior in your own class by overriding the magic “dunder” method __irshift__(self, other) in your class definition.

The expression x >>= y is syntactical sugar for the longer-form x = x >> y :

Related Tutorial: Python In-Place Bitwise Right-Shift

Python In-Place Bitwise Left-Shift

Python’s in-place bitwise left-shift operator x <<= y calculates the left-shift operation x << y , and assigns the result to the first operands variable name x . You can set up the in-place left-shift behavior in your own class by overriding the magic “dunder” method __ilshift__(self, other) in your class definition.

The expression x <<= y is syntactical sugar for the longer-form x = x << y :

Related Tutorial: Python In-Place Bitwise Left-Shift

Python In-Place Magic Methods

The following table provides the names of the magic methods you need to define to enable in-place operators on your custom class:

In the following code example, we create a custom class Data and define our “magic” double-underscore methods so that we can perform in-place computations on objects of this class.

Let’s try these out!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer , and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 572 – Assignment Expressions

The importance of real code, exceptional cases, scope of the target, relative precedence of :=, change to evaluation order, differences between assignment expressions and assignment statements, specification changes during implementation, _pydecimal.py, datetime.py, sysconfig.py, simplifying list comprehensions, capturing condition values, changing the scope rules for comprehensions, alternative spellings, special-casing conditional statements, special-casing comprehensions, lowering operator precedence, allowing commas to the right, always requiring parentheses, why not just turn existing assignment into an expression, with assignment expressions, why bother with assignment statements, why not use a sublocal scope and prevent namespace pollution, style guide recommendations, acknowledgements, a numeric example, appendix b: rough code translations for comprehensions, appendix c: no changes to scope semantics.

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr .

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally).

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.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

During the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other.

The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”.

The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”).

Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below.

However, in order to be compelling , examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code.

Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines.

Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing:

they would write:

Another example illustrates that programmers sometimes do more work to save an extra level of indentation:

This code tries to match pattern2 even if pattern1 has a match (in which case the match on pattern2 is never used). The more efficient rewrite would have been:

Syntax and semantics

In most contexts 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 other than an unparenthesized tuple, 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:

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

Again, this rule is included to avoid two visually similar ways of saying the same thing.

This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

This allows lambda to always bind less tightly than := ; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an any() expression, or a counterexample for all() , for example:

Second, it allows a compact way of updating mutable state from a comprehension, for example:

However, an assignment expression target name cannot be the same as a for -target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

While it’s technically possible to assign consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation [1] will ensure that such cases raise SyntaxError , rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword):

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is expressly invalid. This case also raises SyntaxError :

(The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code.

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or , and , not , and conditional expressions ( A if C else B ). As follows from section “Exceptional cases” above, it is never allowed at the same level as = . In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what’s technically valid or invalid:

Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable:

This PEP recommends always putting spaces around := , similar to PEP 8 ’s recommendation for = when used for assignment, whereas the latter disallows spaces around = used for keyword arguments.)

In order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:

  • In a dict comprehension {X: Y for ...} , Y is currently evaluated before X . We propose to change this so that X is evaluated before Y . (In a dict display like {X: Y} this is already the case, and also in dict((X, Y) for ...) which should clearly be equivalent to the dict comprehension.)

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don’t support the advanced features found in assignment statements:

  • Multiple targets are not directly supported: x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
  • Single assignment targets other than a single NAME are not supported: # No equivalent a [ i ] = x self . rest = []
  • Priority around commas is different: x = 1 , 2 # Sets x to (1, 2) ( x := 1 , 2 ) # Sets x to 1
  • Iterable packing and unpacking (both regular or extended forms) are not supported: # 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 are not supported: # 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)

The following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:

  • for consistency with other similar exceptions, and to avoid locking in an exception name that is not necessarily going to improve clarity for end users, the originally proposed TargetScopeError subclass of SyntaxError was dropped in favour of just raising SyntaxError directly. [3]
  • due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.

Examples from the Python standard library

env_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.

  • Current: env_base = os . environ . get ( "PYTHONUSERBASE" , None ) if env_base : return env_base
  • Improved: if env_base := os . environ . get ( "PYTHONUSERBASE" , None ): return env_base

Avoid nested if and remove one indentation level.

  • Current: if self . _is_special : ans = self . _check_nans ( context = context ) if ans : return ans
  • Improved: if self . _is_special and ( ans := self . _check_nans ( context = context )): return ans

Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)

  • Current: reductor = dispatch_table . get ( cls ) if reductor : rv = reductor ( x ) else : reductor = getattr ( x , "__reduce_ex__" , None ) if reductor : rv = reductor ( 4 ) else : reductor = getattr ( x , "__reduce__" , None ) if reductor : rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )
  • Improved: if reductor := dispatch_table . get ( cls ): rv = reductor ( x ) elif reductor := getattr ( x , "__reduce_ex__" , None ): rv = reductor ( 4 ) elif reductor := getattr ( x , "__reduce__" , None ): rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )

tz is only used for s += tz , moving its assignment inside the if helps to show its scope.

  • Current: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) tz = self . _tzstr () if tz : s += tz return s
  • Improved: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) if tz := self . _tzstr (): s += tz return s

Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without making it harder to understand.

  • Current: while True : line = fp . readline () if not line : break m = define_rx . match ( line ) if m : n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v else : m = undef_rx . match ( line ) if m : vars [ m . group ( 1 )] = 0
  • Improved: while line := fp . readline (): if m := define_rx . match ( line ): n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v elif m := undef_rx . match ( line ): vars [ m . group ( 1 )] = 0

A list comprehension can map and filter efficiently by capturing the condition:

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff ).

Assignment expressions can be used to good effect in the header of an if or while statement:

Particularly with the while loop, this can remove the need to have an infinite loop, an assignment, and a condition. It also creates a smooth parallel between a loop which simply uses a function call as its condition, and one which uses that as its condition but also uses the actual value.

An example from the low-level UNIX world:

Rejected alternative proposals

Proposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above.

A previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions.

Broadly the same semantics as the current proposal, but spelled differently.

Since EXPR as NAME already has meaning in import , except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR – it calls EXPR.__enter__() and assigns the result of that to VAR .)

Additional reasons to prefer := over this spelling include:

  • In if f(x) as y the assignment target doesn’t jump out at you – it just reads like if f x blah blah and it is too similar visually to if f(x) and y .
  • import foo as bar
  • except Exc as var
  • with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

  • NAME = EXPR
  • if NAME := EXPR

reinforces the visual recognition of assignment expressions.

This syntax is inspired by languages such as R and Haskell, and some programmable calculators. (Note that a left-facing arrow y <- f(x) is not possible in Python, as it would be interpreted as less-than and unary minus.) This syntax has a slight advantage over ‘as’ in that it does not conflict with with , except and import , but otherwise is equivalent. But it is entirely unrelated to Python’s other use of -> (function return type annotations), and compared to := (which dates back to Algol-58) it has a much weaker tradition.

This has the advantage that leaked usage can be readily detected, removing some forms of syntactic ambiguity. However, this would be the only place in Python where a variable’s scope is encoded into its name, making refactoring harder.

Execution order is inverted (the indented body is performed first, followed by the “header”). This requires a new keyword, unless an existing keyword is repurposed (most likely with: ). See PEP 3150 for prior discussion on this subject (with the proposed keyword being given: ).

This syntax has fewer conflicts than as does (conflicting only with the raise Exc from Exc notation), but is otherwise comparable to it. Instead of paralleling with expr as target: (which can be useful but can also be confusing), this has no parallels, but is evocative.

One of the most popular use-cases is if and while statements. Instead of a more general solution, this proposal enhances the syntax of these two statements to add a means of capturing the compared value:

This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return '' when done), and completely useless in more complicated cases (e.g. where the condition is f(x) < 0 and you want to capture the value of f(x) ). It also has no benefit to list comprehensions.

Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible use-cases, even in if / while statements.

Another common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.

This brings the subexpression to a location in between the ‘for’ loop and the expression. It introduces an additional language keyword, which creates conflicts. Of the three, where reads the most cleanly, but also has the greatest potential for conflict (e.g. SQLAlchemy and numpy have where methods, as does tkinter.dnd.Icon in the standard library).

As above, but reusing the with keyword. Doesn’t read too badly, and needs no additional language keyword. Is restricted to comprehensions, though, and cannot as easily be transformed into “longhand” for-loop syntax. Has the C problem that an equals sign in an expression can now create a name binding, rather than performing a comparison. Would raise the question of why “with NAME = EXPR:” cannot be used as a statement on its own.

As per option 2, but using as rather than an equals sign. Aligns syntactically with other uses of as for name binding, but a simple transformation to for-loop longhand would create drastically different semantics; the meaning of with inside a comprehension would be completely different from the meaning as a stand-alone statement, while retaining identical syntax.

Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name bindings. The only keyword that can be repurposed to this task is with , thus giving it sneakily different semantics in a comprehension than in a statement; alternatively, a new keyword is needed, with all the costs therein.

There are two logical precedences for the := operator. Either it should bind as loosely as possible, as does statement-assignment; or it should bind more tightly than comparison operators. Placing its precedence between the comparison and arithmetic operators (to be precise: just lower than bitwise OR) allows most uses inside while and if conditions to be spelled without parentheses, as it is most likely that you wish to capture the value of something, then perform a comparison on it:

Once find() returns -1, the loop terminates. If := binds as loosely as = does, this would capture the result of the comparison (generally either True or False ), which is less useful.

While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for := has been made as close as possible to that of = (with the exception that it binds tighter than comma).

Some critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent:

(With the current version of the proposal, the latter would be equivalent to ((point := x), y) .)

However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence:

The less confusing option is to make := bind more tightly than comma.

It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant:

Frequently Raised Objections

C and its derivatives define the = operator as an expression, rather than a statement as is Python’s way. This allows assignments in more contexts, including contexts where comparisons are more common. The syntactic similarity between if (x == y) and if (x = y) belies their drastically different semantics. Thus this proposal uses := to clarify the distinction.

The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create externally-visible names. This is no different from for loops or other constructs, and can be solved the same way: del the name once it is no longer needed, or prefix it with an underscore.

(The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2] )

As expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8 , two recommendations are suggested.

  • If either assignment statements or assignment expressions can be used, prefer statements; they are a clear declaration of intent.
  • If using assignment expressions would lead to ambiguity about execution order, restructure it to use statements instead.

The authors wish to thank Alyssa Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation.

Appendix A: Tim Peters’s findings

Here’s a brief essay Tim Peters wrote on the topic.

I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of:

instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled:

is a vast improvement over the briefer:

The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane.

In other cases, combining related logic made it harder to understand, such as rewriting:

as the briefer:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isn’t wired that way.

But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better than sparse”. For example, I have many functions that return None or 0 to communicate “I have nothing useful to return in this case, but since that’s expected often I’m not going to annoy you with an exception”. This is essentially the same as regular expression search functions returning None when there is no match. So there was lots of code of the form:

I find that clearer, and certainly a bit less typing and pattern-matching reading, as:

It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me!

There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s copy() function in copy.py :

The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”:

Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it.

A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level:

That if is about as long as I want my lines to get, but remains easy to follow.

So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d certainly use it more often than ternary if , but significantly less often than augmented assignment.

I have another example that quite impressed me at the time.

Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration):

It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding.

If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression.

To my eyes, the original form is harder to understand:

This appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding.

Since [x for ...] is equivalent to list(x for ...) these examples all use list comprehensions without loss of generality. And since these examples are meant to clarify edge cases of the rules, they aren’t trying to look like real code.

Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope).

Let’s start with a reminder of what code is generated for a generator expression without assignment expression.

  • Original code (EXPR usually references VAR): def f (): a = [ EXPR for VAR in ITERABLE ]
  • Translation (let’s not worry about name conflicts): def f (): def genexpr ( iterator ): for VAR in iterator : yield EXPR a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a simple assignment expression.

  • Original code: def f (): a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): if False : TARGET = None # Dead code to ensure TARGET is a local variable def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a global TARGET declaration in f() .

  • Original code: def f (): global TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): global TARGET def genexpr ( iterator ): global TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Or instead let’s add a nonlocal TARGET declaration in f() .

  • Original code: def g (): TARGET = ... def f (): nonlocal TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def g (): TARGET = ... def f (): nonlocal TARGET def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Finally, let’s nest two comprehensions.

  • Original code: def f (): a = [[ TARGET := i for i in range ( 3 )] for j in range ( 2 )] # I.e., a = [[0, 1, 2], [0, 1, 2]] print ( TARGET ) # prints 2
  • Translation: def f (): if False : TARGET = None def outer_genexpr ( outer_iterator ): nonlocal TARGET def inner_generator ( inner_iterator ): nonlocal TARGET for i in inner_iterator : TARGET = i yield i for j in outer_iterator : yield list ( inner_generator ( range ( 3 ))) a = list ( outer_genexpr ( range ( 2 ))) print ( TARGET )

Because it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example:

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0572.rst

Last modified: 2023-10-11 12:05:51 GMT

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
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Object & Classes
  • 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 Questions and Answers
  • Python Useful Resources
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
  • 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.

Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise

Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and returns a sum of two operands as a result.

Python includes the operator module that includes underlying methods for each operator. For example, the + operator calls the operator.add(a,b) method.

Above, expression 5 + 6 is equivalent to the expression operator.add(5, 6) and operator.__add__(5, 6) . Many function names are those used for special methods, without the double underscores (dunder methods). For backward compatibility, many of these have functions with the double underscores kept.

Python includes the following categories of operators:

Arithmetic Operators

Assignment operators, comparison operators, logical operators, identity operators, membership test operators, bitwise operators.

Arithmetic operators perform the common mathematical operation on the numeric operands.

The arithmetic operators return the type of result depends on the type of operands, as below.

  • If either operand is a complex number, the result is converted to complex;
  • If either operand is a floating point number, the result is converted to floating point;
  • If both operands are integers, then the result is an integer and no conversion is needed.

The following table lists all the arithmetic operators in Python:

The assignment operators are used to assign values to variables. The following table lists all the arithmetic operators in Python:

The comparison operators compare two operands and return a boolean either True or False. The following table lists comparison operators in Python.

The logical operators are used to combine two boolean expressions. The logical operations are generally applicable to all objects, and support truth tests, identity tests, and boolean operations.

The identity operators check whether the two objects have the same id value e.i. both the objects point to the same memory location.

The membership test operators in and not in test whether the sequence has a given item or not. For the string and bytes types, x in y is True if and only if x is a substring of y .

Bitwise operators perform operations on binary operands.

  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles
  • Python Questions & Answers
  • Python Skill Test
  • Python Latest Articles
  • Python - Home
  • Python - Introduction
  • Python - Syntax
  • Python - Comments
  • Python - Variables
  • Python - Data Types
  • Python - Numbers
  • Python - Type Casting
  • Python - Operators
  • Python - Booleans
  • Python - Strings
  • Python - Lists
  • Python - Tuples
  • Python - Sets
  • Python - Dictionary
  • Python - If Else
  • Python - While Loop
  • Python - For Loop
  • Python - Continue Statement
  • Python - Break Statement
  • Python - Functions
  • Python - Lambda Function
  • Python - Scope of Variables
  • Python - Modules
  • Python - Date & Time
  • Python - Iterators
  • Python - JSON
  • Python - File Handling
  • Python - Try Except
  • Python - Arrays
  • Python - Classes/Objects
  • Python - Inheritance
  • Python - Decorators
  • Python - RegEx
  • Python - Operator Overloading
  • Python - Built-in Functions
  • Python - Keywords
  • Python - String Methods
  • Python - File Handling Methods
  • Python - List Methods
  • Python - Tuple Methods
  • Python - Set Methods
  • Python - Dictionary Methods
  • Python - Math Module
  • Python - cMath Module
  • Python - Data Structures
  • Python - Examples
  • Python - Q&A
  • Python - Interview Questions
  • Python - NumPy
  • Python - Pandas
  • Python - Matplotlib
  • Python - SciPy
  • Python - Seaborn

AlphaCodingSkills

  • Programming Languages
  • Web Technologies
  • Database Technologies
  • Microsoft Technologies
  • Python Libraries
  • Data Structures
  • Interview Questions
  • PHP & MySQL
  • C++ Standard Library
  • C Standard Library
  • Java Utility Library
  • Java Default Package
  • PHP Function Reference

Python - Assignment Operator Overloading

Assignment operator is a binary operator which means it requires two operand to produce a new value. Following is the list of assignment operators and corresponding magic methods that can be overloaded in Python.

Example: overloading assignment operator

In the example below, assignment operator (+=) is overloaded. When it is applied with a vector object, it increases x and y components of the vector by specified number. for example - (10, 15) += 5 will produce (10+5, 15+5) = (15, 20).

The output of the above code will be:

AlphaCodingSkills Android App

  • Data Structures Tutorial
  • Algorithms Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQLi Tutorial
  • Java Tutorial
  • Scala Tutorial
  • C++ Tutorial
  • C# Tutorial
  • PHP Tutorial
  • MySQL Tutorial
  • SQL Tutorial
  • PHP Function reference
  • C++ - Standard Library
  • Java.lang Package
  • Ruby Tutorial
  • Rust Tutorial
  • Swift Tutorial
  • Perl Tutorial
  • HTML Tutorial
  • CSS Tutorial
  • AJAX Tutorial
  • XML Tutorial
  • Online Compilers
  • QuickTables
  • NumPy Tutorial
  • Pandas Tutorial
  • Matplotlib Tutorial
  • SciPy Tutorial
  • Seaborn Tutorial

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in python.

' src=

Last Updated on June 8, 2023 by Prepbytes

assignment operator in python class

To fully comprehend the assignment operators in Python, it is important to have a basic understanding of what operators are. Operators are utilized to carry out a variety of operations, including mathematical, bitwise, and logical operations, among others, by connecting operands. Operands are the values that are acted upon by operators. In Python, the assignment operator is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is the most commonly used operator in Python. In this article, we will explore the assignment operator in Python, how it works, and its different types.

What is an Assignment Operator in Python?

The assignment operator in Python is used to assign a value to a variable. The assignment operator is represented by the equals sign (=), and it is used to assign a value to a variable. When an assignment operator is used, the value on the right-hand side is assigned to the variable on the left-hand side. This is a fundamental operation in programming, as it allows developers to store data in variables that can be used throughout their code.

For example, consider the following line of code:

Explanation: In this case, the value 10 is assigned to the variable a using the assignment operator. The variable a now holds the value 10, and this value can be used in other parts of the code. This simple example illustrates the basic usage and importance of assignment operators in Python programming.

Types of Assignment Operator in Python

There are several types of assignment operator in Python that are used to perform different operations. Let’s explore each type of assignment operator in Python in detail with the help of some code examples.

1. Simple Assignment Operator (=)

The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is:

Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example

Explanation: In this case, the value 25 is assigned to the variable a using the simple assignment operator. The variable a now holds the value 25.

2. Addition Assignment Operator (+=)

The addition assignment operator is used to add a value to a variable and store the result in the same variable. The syntax for the addition assignment operator is:

Here, the value on the right-hand side is added to the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is incremented by 5 using the addition assignment operator. The result, 15, is then printed to the console.

3. Subtraction Assignment Operator (-=)

The subtraction assignment operator is used to subtract a value from a variable and store the result in the same variable. The syntax for the subtraction assignment operator is

Here, the value on the right-hand side is subtracted from the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is decremented by 5 using the subtraction assignment operator. The result, 5, is then printed to the console.

4. Multiplication Assignment Operator (*=)

The multiplication assignment operator is used to multiply a variable by a value and store the result in the same variable. The syntax for the multiplication assignment operator is:

Here, the value on the right-hand side is multiplied by the variable on the left-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is multiplied by 5 using the multiplication assignment operator. The result, 50, is then printed to the console.

5. Division Assignment Operator (/=)

The division assignment operator is used to divide a variable by a value and store the result in the same variable. The syntax for the division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 5 using the division assignment operator. The result, 2.0, is then printed to the console.

6. Modulus Assignment Operator (%=)

The modulus assignment operator is used to find the remainder of the division of a variable by a value and store the result in the same variable. The syntax for the modulus assignment operator is

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the remainder is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the modulus assignment operator. The remainder, 1, is then printed to the console.

7. Floor Division Assignment Operator (//=)

The floor division assignment operator is used to divide a variable by a value and round the result down to the nearest integer, and store the result in the same variable. The syntax for the floor division assignment operator is:

Here, the variable on the left-hand side is divided by the value on the right-hand side, and the result is rounded down to the nearest integer. The rounded result is then stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is divided by 3 using the floor division assignment operator. The result, 3, is then printed to the console.

8. Exponentiation Assignment Operator (**=)

The exponentiation assignment operator is used to raise a variable to the power of a value and store the result in the same variable. The syntax for the exponentiation assignment operator is:

Here, the variable on the left-hand side is raised to the power of the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example

Explanation: In this case, the value of a is raised to the power of 3 using the exponentiation assignment operator. The result, 8, is then printed to the console.

9. Bitwise AND Assignment Operator (&=)

The bitwise AND assignment operator is used to perform a bitwise AND operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise AND assignment operator is:

Here, the variable on the left-hand side is ANDed with the value on the right-hand side using the bitwise AND operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ANDed with 3 using the bitwise AND assignment operator. The result, 2, is then printed to the console.

10. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator is used to perform a bitwise OR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise OR assignment operator is:

Here, the variable on the left-hand side is ORed with the value on the right-hand side using the bitwise OR operator, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is ORed with 3 using the bitwise OR assignment operator. The result, 7, is then printed to the console.

11. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator is used to perform a bitwise XOR operation on the binary representation of a variable and a value, and store the result in the same variable. The syntax for the bitwise XOR assignment operator is:

Here, the variable on the left-hand side is XORed with the value on the right-hand side using the bitwise XOR operator, and the result are stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is XORed with 3 using the bitwise XOR assignment operator. The result, 5, is then printed to the console.

12. Bitwise Right Shift Assignment Operator (>>=)

The bitwise right shift assignment operator is used to shift the bits of a variable to the right by a specified number of positions, and store the result in the same variable. The syntax for the bitwise right shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the right by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Explanation: In this case, the value of a is shifted 2 positions to the right using the bitwise right shift assignment operator. The result, 2, is then printed to the console.

13. Bitwise Left Shift Assignment Operator (<<=)

The bitwise left shift assignment operator is used to shift the bits of a variable to the left by a specified number of positions, and store the result in the same variable. The syntax for the bitwise left shift assignment operator is:

Here, the variable on the left-hand side has its bits shifted to the left by the number of positions specified by the value on the right-hand side, and the result is stored back in the variable on the left-hand side. For example,

Conclusion Assignment operator in Python is used to assign values to variables, and it comes in different types. The simple assignment operator (=) assigns a value to a variable. The augmented assignment operators (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=) perform a specified operation and assign the result to the same variable in one step. The modulus assignment operator (%) calculates the remainder of a division operation and assigns the result to the same variable. The bitwise assignment operators (&=, |=, ^=, >>=, <<=) perform bitwise operations and assign the result to the same variable. The bitwise right shift assignment operator (>>=) shifts the bits of a variable to the right by a specified number of positions and stores the result in the same variable. The bitwise left shift assignment operator (<<=) shifts the bits of a variable to the left by a specified number of positions and stores the result in the same variable. These operators are useful in simplifying and shortening code that involves assigning and manipulating values in a single step.

Here are some Frequently Asked Questions on Assignment Operator in Python:

Q1 – Can I use the assignment operator to assign multiple values to multiple variables at once? Ans – Yes, you can use the assignment operator to assign multiple values to multiple variables at once, separated by commas. For example, "x, y, z = 1, 2, 3" would assign the value 1 to x, 2 to y, and 3 to z.

Q2 – Is it possible to chain assignment operators in Python? Ans – Yes, you can chain assignment operators in Python to perform multiple operations in one line of code. For example, "x = y = z = 1" would assign the value 1 to all three variables.

Q3 – How do I perform a conditional assignment in Python? Ans – To perform a conditional assignment in Python, you can use the ternary operator. For example, "x = a (if a > b) else b" would assign the value of a to x if a is greater than b, otherwise it would assign the value of b to x.

Q4 – What happens if I use an undefined variable in an assignment operation in Python? Ans – If you use an undefined variable in an assignment operation in Python, you will get a NameError. Make sure you have defined the variable before trying to assign a value to it.

Q5 – Can I use assignment operators with non-numeric data types in Python? Ans – Yes, you can use assignment operators with non-numeric data types in Python, such as strings or lists. For example, "my_list += [4, 5, 6]" would append the values 4, 5, and 6 to the end of the list named my_list.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.

Every dunder method in Python

Trey Hunner smiling in a t-shirt against a yellow wall

You've just made a class. You made a __init__ method. Now what?

Python includes tons of dunder methods ("double underscore" methods) which allow us to deeply customize how our custom classes interact with Python's many features. What dunder methods could you add to your class to make it friendly for other Python programmers who use it?

Let's take a look at every dunder method in Python , with a focus on when each method is useful.

Note that the Python documentation refers to these as special methods and notes the synonym "magic method" but very rarely uses the term "dunder method". However, "dunder method" is a fairly common Python colloquialism, as noted in my unofficial Python glossary .

You can use the links scattered throughout this page for more details on any particular dunder method. For a list of all of them, see the cheat sheet in the final section.

The 3 essential dunder methods 🔑

There are 3 dunder methods that most classes should have: __init__ , __repr__ , and __eq__ .

The __init__ method is the initializer (not to be confused with the constructor ), the __repr__ method customizes an object's string representation, and the __eq__ method customizes what it means for objects to be equal to one another.

The __repr__ method is particularly helpful at the the Python REPL and when debugging.

Equality and hashability 🟰

In addition to the __eq__ method, Python has 2 other dunder methods for determining the "value" of an object in relation to other objects.

Python's __eq__ method typically returns True , False , or NotImplemented (if objects can't be compared). The default __eq__ implementation relies on the is operator, which checks for identity .

The default implementation of __ne__ calls __eq__ and negates any boolean return value given (or returns NotImplemented if __eq__ did). This default behavior is usually "good enough", so you'll almost never see __ne__ implemented .

Hashable objects can be used as keys in dictionaries or values in sets. All objects in Python are hashable by default, but if you've written a custom __eq__ method then your objects won't be hashable without a custom __hash__ method. But the hash value of an object must never change or bad things will happen so typically only immutable objects implement __hash__ .

For implementing equality checks, see __eq__ in Python . For implementing hashability, see making hashable objects in Python .

Orderability ⚖️

Python's comparison operators ( < , > , <= , >= ) can all be overloaded with dunder methods as well. The comparison operators also power functions that rely on the relative ordering of objects, like sorted , min , and max .

If you plan to implement all of these operators in the typical way (where x < y would be the same as asking y > x ) then the total_ordering decorator from Python's functools module will come in handy.

Type conversions and string formatting ⚗️

Python has a number of dunder methods for converting objects to a different type.

The __bool__ function is used for truthiness checks, though __len__ is used as a fallback.

If you needed to make an object that acts like a number (like decimal.Decimal or fractions.Fraction ), you'll want to implement __int__ , __float__ , and __complex__ so your objects can be converted to other numbers. If you wanted to make an object that could be used in a memoryview or could otherwise be converted to bytes , you'll want a __bytes__ method.

The __format__ and __repr__ methods are different string conversion flavors. Most string conversions rely the __str__ method, but the default __str__ implementation simply calls __repr__ .

The __format__ method is used by all f-string conversions , by the str class's format method, and by the (rarely used) built-in format function. This method allows datetime objects to support custom format specifiers .

Context managers 🚪

A context manager is an object that can be used in a with block.

For more on context managers see, what is a context manager and creating a context manager .

Containers and collections 🗃️

Collections (a.k.a. containers) are essentially data structures or objects that act like data stuctures. Lists, dictionaries, sets, strings, and tuples are all examples of collections.

The __iter__ method is used by the iter function and for all forms of iteration: for loops , comprehensions , tuple unpacking , and using * for iterable unpacking .

While the __iter__ method is necessary for creating a custom iterable, the __next__ method is necessary for creating a custom iterator (which is much less common). The __missing__ method is only ever called by the dict class on itself, unless another class decides to implement __missing__ . The __length_hint__ method supplies a length guess for structures which do not support __len__ so that lists or other structures can be pre-sized more efficiently.

Also see: the iterator protocol , implementing __len__ , and implementing __getitem__ .

Callability ☎️

Functions, classes, and all other callable objects rely on the __call__ method.

When a class is called, its metaclass 's __call__ method is used. When a class instance is called, the class's __call__ method is used.

For more on callability, see Callables: Python's "functions" are sometimes classes .

Arithmetic operators ➗

Python's dunder methods are often described as a tool for "operator overloading". Most of this "operator overloading" comes in the form of Python's various arithmetic operators.

There are two ways to break down the arithmetic operators:

  • Mathematical (e.g. + , - , * , / , % ) versus bitwise (e.g. & , | , ^ , >> , ~ )
  • Binary (between 2 values, like x + y ) versus unary (before 1 value, like +x )

The mathematical operators are much more common than the bitwise ones and the binary ones are a bit more common than the unary ones.

These are the binary mathematical arithmetic operators:

Each of these operators includes left-hand and right-hand methods. If x.__add__(y) returns NotImplemented , then y.__radd__(x) will be attempted. See arithmetic dunder methods for more.

These are the binary bitwise arithmetic operators:

These are Python's unary arithmetic operators:

The unary + operator typically has no effect , though some objects use it for a specific operation. For example using + on collections.Counter objects will remove non-positive values.

Python's arithmetic operators are often used for non-arithmetic ends: sequences use + to concatenate and * to self-concatenate and sets use & for intersection, | for union, - for asymmetric difference, and ^ for symmetric difference. Arithmetic operators are sometimes overloaded for more creative uses too. For example, pathlib.Path objects use / to create child paths .

In-place arithmetic operations ♻️

Python includes many dunder methods for in-place operations. If you're making a mutable object that supports any of the arithmetic operations, you'll want to implement the related in-place dunder method(s) as well.

All of Python's binary arithmetic operators work in augmented assignment statements , which involve using an operator followed by the = sign to assign to an object while performing an operation on it.

Augmented assignments on mutable objects are expected to mutate the original object , thanks to the mutable object implementing the appropriate dunder method for in-place arithmetic.

When no dunder method is found for an in-place operation, Python performs the operation followed by an assignment. Immutable objects typically do not implement dunder methods for in-place operations , since they should return a new object instead of changing the original.

Built-in math functions 🧮

Python also includes dunder methods for many math-related functions, both built-in functions and some functions in the math library.

Python's divmod function performs integer division ( // ) and a modulo operation ( % ) at the same time. Note that, just like the many binary arithmetic operators, divmod will also check for an __rvidmod__ method if it needs to ask the second argument to handle the operation.

The __index__ method is for making integer-like objects. This method losslessly converts to an integer, unlike __int__ which may perform a "lossy" integer conversion (e.g. from float to int ). It's used by operations that require true integers, such as slicing , indexing, and bin , hex , and oct functions ( example ).

Attribute access 📜

Python even includes dunder methods for controlling what happens when you access, delete, or assign any attribute on an object!

The __getattribute__ method is called for every attribute access, while the __getattr__ method is only called after Python fails to find a given attribute. All method calls and attribute accesses call __getattribute__ so implementing it correctly is challenging (due to accidental recursion ).

The __dir__ method should return an iterable of attribute names (as strings). When the dir function calls __dir__ , it converts the returned iterable into a sorted list (like sorted does).

The built-in getattr , setattr , and delattr functions correspond to the dunder methods of the same name, but they're only intended for dynamic attribute access (not all attribute accesses).

Metaprogramming 🪄

Now we're getting into the really unusual dunder methods. Python includes many dunder methods for metaprogramming-related features.

The __prepare__ method customizes the dictionary that's used for a class's initial namespace. This is used to pre-populate dictionary values or customize the dictionary type ( silly example ).

The __instancecheck__ and __subclasscheck__ methods override the functionality of isinstance and issubclass . Python's ABCs use these to practice goose typing ( duck typing while type checking).

The __init_subclass__ method allows classes to hook into subclass initialization ( example ). Classes also have a __subclasses__ method (on their metaclass ) but it's not typically overridden.

Python calls __mro_entries__ during class inheritance for any base classes that are not actually classes. The typing.NamedTuple function uses this to pretend it's a class ( see here ).

The __class_getitem__ method allows a class to be subscriptable ( without its metaclass needing a __getitem__ method). This is typically used for enabling fancy type annotations (e.g. list[int] ).

Descriptors 🏷️

Descriptors are objects that, when attached to a class, can hook into the access of the attribute name they're attached to on that class.

The descriptor protocol is mostly a feature that exists to make Python's property decorator work, though it is also used by a number of third-party libraries.

Implementing a low-level memory array? You need Python's buffer protocol .

The __release_buffer__ method is called when the buffer that's returned from __buffer__ is deleted.

Python's buffer protocol is typically implemented in C, since it's meant for low level objects.

Asynchronous operations 🤹

Want to implement an asynchronous context manager? You need these dunder methods:

  • __aenter__ : just like __enter__ , but it returns an awaitable object
  • __aexit__ : just like __exit__ , but it returns an awaitable object

Need to support asynchronous iteration? You need these dunder methods:

  • __aiter__ : must return an asynchronous iterator
  • __anext__ : like __next__ or non-async iterators, but this must return an awaitable object and this should raise StopAsyncIteration instead of StopIteration

Need to make your own awaitable object? You need this dunder method:

  • __await__ : returns an iterator

I have little experience with custom asynchronous objects, so look elsewhere for more details.

Construction and finalizing 🏭

The last few dunder methods are related to object creation and destruction.

Calling a class returns a new class instance thanks to the __new__ method. The __new__ method is Python's constructor method , though unlike constructors in many programming languages, you should almost never define your own __new__ method. To control object creation, prefer the initializer ( __init__ ), not the constructor ( __new__ ). Here's an odd __new__ example .

You could think of __del__ as a "destructor" method, though it's actually called the finalizer method . Just before an object is deleted, its __del__ method is called ( example ). Files implement a __del__ method that closes the file and any binary file buffer that it may be linked to.

Library-specific dunder methods 🧰

Some standard library modules define custom dunder methods that aren't used anywhere else:

  • dataclasses support a __post_init__ method
  • abc.ABC classes have a __subclasshook__ method which abc.ABCMeta calls in its __subclasscheck__ method (more in goose typing )
  • Path-like objects have a __fspath__ method, which returns the file path as a string
  • Python's copy module will use the __copy__ and __deepcopy__ methods if present
  • Pickling relies on __getnewargs_ex__ or __getargs__ , though __getstate__ and __setstate__ can customize further and __reduce__ or __reduce_ex__ are even lower-level
  • sys.getsizeof relies on the __sizeof__ method to get an object's size (in bytes)

Dunder attributes 📇

In addition to dunder methods, Python has many non-method dunder attributes .

Here are some of the more common dunder attributes you'll see:

  • __name__ : name of a function, classes, or module
  • __module__ : module name for a function or class
  • __doc__ : docstring for a function, class, or module
  • __class__ : an object's class (call Python's type function instead)
  • __dict__ : most objects store their attributes here (see where are attributes stored? )
  • __slots__ : classes using this are more memory efficient than classes using __dict__
  • __match_args__ : classes can define a tuple noting the significance of positional attributes when the class is used in structural pattern matching ( match - case )
  • __mro__ : a class's method resolution order used when for attribute lookups and super() calls
  • __bases__ : the direct parent classes of a class
  • __file__ : the file that defined the module object (though not always present!)
  • __wrapped__ : functions decorated with functools.wraps use this to point to the original function
  • __version__ : commonly used for noting the version of a package
  • __all__ : modules can use this to customize the behavior of from my_module import *
  • __debug__ : running Python with -O sets this to False and disables Python's assert statements

Those are only the more commonly seen dunder attributes. Here are some more:

  • Functions have __defaults__ , __kwdefaults__ , __code__ , __globals__ , and __closure__
  • Both functions and classes have __qualname__ , __annotations__ , and __type_params__
  • Instance methods have __func__ and __self__
  • Modules may also have __loader__ , __package__ , __spec__ , and __cached__ attributes
  • Packages have a __path__ attribute
  • Exceptions have __traceback__ , __notes__ , __context__ , __cause__ , and __suppress_context__
  • Descriptors use __objclass__
  • Metaclasses use __classcell__
  • Python's weakref module uses __weakref__
  • Generic aliases have __origin__ , __args__ , __parameters__ , and __unpacked__
  • The sys module has __stdout__ and __stderr__ which point to the original stdout and stderr versions

Additionally, these dunder attributes are used by various standard library modules: __covariant__ , __contravariant__ , __infer_variance__ , __bound__ , __constraints__ . And Python includes a built-in __import__ function which you're not supposed to use ( importlib.import_module is preferred) and CPython has a __builtins__ variable that points to the builtins module (but this is an implementation detail and builtins should be explicitly imported when needed instead). Also importing from the __future__ module can enable specific Python feature flags and Python will look for a __main__ module within packages to make them runnable as CLI scripts.

And that's just most of the dunder attribute names you'll find floating around in Python. 😵

Every dunder method: a cheat sheet ⭐

This is every Python dunder method organized in categories and ordered very roughly by the most commonly seen methods first. Some caveats are noted below.

The above table has a slight but consistent untruth . Most of these dunder methods are not actually called on an object directly but are instead called on the type of that object: type(x).__add__(x, y) instead of x.__add__(y) . This distinction mostly matters with metaclass methods.

I've also purposely excluded library-specific dunder methods (like __post_init__ ) and dunder methods you're unlikely to ever define (like __subclasses__ ). See those below.

So, Python includes 103 "normal" dunder methods, 12 library-specific dunder methods, and at least 52 other dunder attributes of various types. That's over 150 unique __dunder__ names! I do not recommend memorizing these: let Python do its job and look up the dunder method or attribute that you need to implement/find whenever you need it.

Keep in mind that you're not meant to invent your own dunder methods . Sometimes you'll see third-party libraries that do invent their own dunder method, but this isn't encouraged and it can be quite confusing for users who run across such methods and assume they're " real " dunder methods.

A Python tip every week

Need to fill-in gaps in your Python skills?

Sign up for my Python newsletter where I share one of my favorite Python tips every week .

Need to fill-in gaps in your Python skills ? I send weekly emails designed to do just that.

assignment operator in python class

Hiring? Flexiple helps you build your dream team of  developers   and  designers .

Python Operators

Harsh Pandey

Harsh Pandey

Last updated on 19 Mar 2024

Python, one of the most popular programming languages today, is known for its simplicity and readability. One fundamental aspect of Python that contributes to its ease of use is its operators. Operators are the constructs which can manipulate the value of operands. In this blog, we'll explore the different types of operators available in Python and their applications.

What Are Python Operators?

Operators in Python are special symbols or keywords that are used to perform operations on one or more operands. An operand can be a value, a variable, or an expression. Operators are the building blocks of Python programs and are used to perform tasks like arithmetic calculations, logical comparisons, and memory operations.

Types Of Python Operators

The various types of operators in python are:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Arithmetic Operators In Python

Arithmetic operators in Python are used to perform basic mathematical operations and are fundamental to any kind of numerical manipulation in Python programming. These operators include addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floor division (//).

  • Addition (+) Adds two operands. For example. result = 3 + 2 print(result) # Output: 5
  • Subtraction (-) Subtracts the right operand from the left operand. result = 5 - 3 print(result) # Output: 2
  • Multiplication (*) Multiplies two operands. result = 4 * 3 print(result) # Output: 12
  • Division (/) Divides the left operand by the right operand. The result is a floating-point number. result = 8 / 2 print(result) # Output: 4.0
  • Modulus (%) Returns the remainder of the division. result = 5 % 2 print(result) # Output: 1
  • Exponentiation (**) Raises the first operand to the power of the second operand. result = 3 ** 2 print(result) # Output: 9
  • Floor Division (//) Performs division but discards the fractional part, returning an integer result. result = 7 // 2 print(result) # Output: 3

Understanding these arithmetic operators is essential for anyone beginning with Python, as they are used widely in various types of numerical calculations and data manipulation tasks.

Comparison Operators In Python

Comparison operators in Python are used to compare values. They evaluate to either True or False based on the condition. These operators are essential in decision-making processes in Python scripts.

  • Equal to (==) Checks if the values of two operands are equal. print(5 == 5) # Output: True print(5 == 3) # Output: False
  • Not Equal to (!=) Checks if the values of two operands are not equal. print(5 != 3) # Output: True print(5 != 5) # Output: False
  • Greater than (>) Checks if the value of the left operand is greater than the right operand. print(5 > 3) # Output: True print(3 > 5) # Output: False
  • Less than (<) Checks if the value of the left operand is less than the right operand. print(3 < 5) # Output: True print(5 < 3) # Output: False
  • Greater than or Equal to (>=) Checks if the left operand is greater than or equal to the right operand. print(5 >= 5) # Output: True print(4 >= 5) # Output: False
  • Less than or Equal to (<=) Checks if the left operand is less than or equal to the right operand. print(3 <= 5) # Output: True print(5 <= 3) # Output: False

Understanding these comparison operators is crucial for controlling the flow of a Python program, as they are commonly used in conditional statements and loops to evaluate conditions and make decisions.

Logical Operators In Python

Logical operators in Python are used to combine conditional statements, and they are fundamental in controlling the flow of logic in Python code. These operators include and, or, and not, each serving a specific purpose in evaluating conditions.

  • and Operator The and operator returns True if both the operands (conditions) are true. print((5 > 3) and (5 > 4)) # Output: True print((5 > 3) and (5 < 4)) # Output: False
  • or Operator The or operator returns True if at least one of the operands is true. print((5 > 3) or (5 < 4)) # Output: True print((5 < 3) or (5 < 4)) # Output: False
  • not Operator The not operator reverses the result of the condition. It returns True if the condition is false and vice versa. print(not(5 > 3)) # Output: False print(not(5 < 3)) # Output: True

Logical operators are integral in Python for building complex logical expressions, making them essential in decision-making structures like if-else statements and loops.

Bitwise Operators In Python

Bitwise operators in Python are used to perform operations on binary numbers at the bit level. These operators are essential for manipulating individual bits and performing bit-by-bit operations.

  • AND Operator (&) The & operator performs a bitwise AND, where each bit of the output is 1 if both corresponding bits of the operand are 1. print(5 & 3) # Output: 1
  • OR Operator (|) The | operator performs a bitwise OR, where each bit of the output is 1 if at least one of the corresponding bits of the operands is 1. print(5 | 3) # Output: 7
  • XOR Operator (^) The ^ operator performs a bitwise XOR, where each bit of the output is 1 if the corresponding bits of the operands are different. print(5 ^ 3) # Output: 6
  • NOT Operator (~) The ~ operator performs a bitwise NOT, inverting each bit of the number. print(~5) # Output: -6
  • Shift Operators Left Shift (<<): Shifts the bits of the number to the left and fills 0 on voids left as a result. The left operand specifies the value to be shifted, and the right operand specifies the number of positions to shift. print(5 << 1) # Output: 10 Right Shift (>>): Shifts the bits of the number to the right. The left operand specifies the value to be shifted, and the right operand specifies the number of positions to shift. print(5 >> 1) # Output: 2

Bitwise operators are particularly useful in low-level programming, such as device driver writing or protocol development, where manipulation of data at the bit level is crucial.

Assignment Operator In Python

Assignment operators in Python are used to assign values to variables. These operators make the code more concise and improve its readability by combining arithmetic operations with assignment.

  • The Basic Assignment Operator (=) The = operator assigns the value on the right to the variable on the left. x = 10 print(x) # Output: 10
  • Compound Assignment Operators These operators combine assignment with other operations. Add and Assign (+=): Adds the right operand to the left operand and assigns the result to the left operand. x = 5 x += 3 # Same as x = x + 3 print(x) # Output: 8 Subtract and Assign (-=): Subtracts the right operand from the left operand and assigns the result to the left operand. x = 5 x -= 3 # Same as x = x - 3 print(x) # Output: 2 Multiply and Assign (*=): Multiplies the right operand with the left operand and assigns the result to the left operand. x = 5 x *= 3 # Same as x = x * 3 print(x) # Output: 15 Divide and Assign (/=): Divides the left operand by the right operand and assigns the result to the left operand. x = 10 x /= 2 # Same as x = x / 2 print(x) # Output: 5.0

Assignment operators are essential in Python for variable manipulation, simplifying expressions, and making code more efficient and easier to understand.

Identity Operators And Membership Operators In Python

Identity and Membership operators in Python are used to compare the identity of objects and check for membership within data structures, respectively.

Identity Operators

Identity operators compare the memory locations of two objects. There are two identity operators in Python: is and is not.

  • is: Evaluates to true if the variables on either side of the operator point to the same object. x = ["apple", "banana"] y = x print(x is y) # Output: True
  • is not: Evaluates to true if the variables on either side of the operator do not point to the same object. x = ["apple", "banana"] y = ["apple", "banana"] print(x is not y) # Output: True

Membership Operators

Membership operators test if a sequence is presented in an object. The two membership operators in Python are in and not in.

  • in: Returns True if a sequence with the specified value is present in the object. x = ["apple", "banana"] print("banana" in x) # Output: True
  • not in: Returns True if a sequence with the specified value is not present in the object. print("cherry" not in x) # Output: True

Identity and Membership operators are crucial in Python for validating the identity of objects and checking for the presence of elements within various data structures like lists, tuples, and strings. They are widely used in conditional statements and loops to enhance the logic and functionality of Python scripts.

Operators in Python are essential for performing various operations on data. Understanding these operators and their applications is crucial for anyone looking to master Python programming. Whether it's for data manipulation, arithmetic calculations, or logical comparisons, Python operators provide a simple yet powerful tool for developers.

Work with top startups & companies. Get paid on time.

Try a top quality developer for 7 days. pay only if satisfied..

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

  • Ruby on Rails
  • Elasticsearch
  • Google Cloud
  • React Native
  • Contact Details
  • 2093, Philadelphia Pike, DE 19703, Claymont
  • [email protected]
  • Explore jobs
  • We are Hiring!
  • Write for us
  • 2093, Philadelphia Pike DE 19703, Claymont

Copyright @ 2024 Flexiple Inc

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Solve Coding Problems
  • Searching a list of objects in Python
  • Abstract Classes in Python
  • Destructors in Python
  • Access Modifiers in Python : Public, Private and Protected
  • Code introspection in Python
  • Constructors in Python
  • Load CSV data in Tensorflow
  • Merge two DataFrames in PySpark
  • How to Extract Chrome Passwords in Python?
  • Data Processing with Pandas
  • Understanding Recursive Functions with Python
  • How to create telnet client with asyncio in Python
  • Scrapy - Link Extractors
  • Python SQLite - Creating a New Database
  • Stacked Bar Chart With Selection Using Altair in Python
  • Multiprocessing with NumPy Arrays
  • __getslice__ in Python
  • Python | super() in single inheritance
  • Scraping dynamic content using Python-Scrapy

How to Change Class Attributes in Python

In Python, editing class attributes involves modifying the characteristics or properties associated with a class. Class attributes are shared by all instances of the class and play an important role in defining the behavior and state of objects within the class. In this article, we will explore different approaches through which we can edit class attributes in Python.

Change Class Attributes in Python

Below are the ways to edit class attributes in Python :

  • Using Direct Assignment
  • Using setattr() function
  • Using Class method
  • Using a property decorator

Edit Class Attributes Using Direct Assignment

In this example, we use the direct assignment approach to edit the class attribute website of the Geeks class, initially set to “ GeeksforGeeks “. After direct assignment, we print the original and edited values, printing the update to “ GFG “.

Edit Class Attributes Using setattr() function

In this example, we use the setattr() function to dynamically edit the class attribute website of the Geeks class, initially set to “ GeeksforGeeks “. After using setattr(), we print the original and edited values, demonstrating the modification to “ GFG “.

Edit Class Attributes Using Class method (@classmethod)

In this example, we define a class method update_website decorated with @classmethod within the Geeks class, allowing us to modify the class attribute website. The original value is printed, and then the class method is utilized to update the attribute to “ GFG “, showcasing the edited value.

Edit Class Attributes Using a property decorator

In this example, the Geeks class uses a property decorator to create a getter and setter for the private attribute _website . The original value is obtained using the getter, and then the property setter is used to update the attribute to “ GFG “. The final value is printed, demonstrating the successful edit.

Please Login to comment...

  • python-oop-concepts
  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 10 Best Skillshare Alternatives in 2024
  • 10 Best Task Management Apps for Android in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Python Tutorials: Assignment Operators In python

    assignment operator in python class

  2. Python Operator

    assignment operator in python class

  3. Python For Beginners

    assignment operator in python class

  4. Assignment Operators in Python

    assignment operator in python class

  5. Python 3 Tutorial

    assignment operator in python class

  6. PPT

    assignment operator in python class

VIDEO

  1. Assignment Operator

  2. Assignment

  3. Assignment Statement ll python ll Animation ll class-6 ll

  4. Python Assignment Operator #python #assignmentoperators #pythonoperators #operatorsinpython

  5. Assignment Operators in python #python #operator

  6. Python

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

    Use Python's assignment operator to write assignment statements; Take advantage of augmented assignments in Python; Explore assignment variants, ... Another example of implicit assignments is the current instance of a class, which in Python is called self by convention. This name implicitly gets a reference to the current object whenever you ...

  2. Assignment Operators in Python

    So, Assignment Operators are used to assigning values to variables. Operator. Description. Syntax. =. Assign value of right side of expression to left side operand. x = y + z. +=. Add and Assign: Add right side operand with left side operand and then assign to left operand.

  3. class

    101. The way you describe it is absolutely not possible. Assignment to a name is a fundamental feature of Python and no hooks have been provided to change its behavior. However, assignment to a member in a class instance can be controlled as you want, by overriding .__setattr__ (). class MyClass(object):

  4. Python Assignment Operators

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

  5. 9. Classes

    Note how the local assignment (which is default) didn't change scope_test's binding of spam.The nonlocal assignment changed scope_test's binding of spam, and the global assignment changed the module-level binding.. You can also see that there was no previous binding for spam before the global assignment.. 9.3. A First Look at Classes¶. Classes introduce a little bit of new syntax, three new ...

  6. operator

    In-place Operators¶. Many operations have an "in-place" version. Listed below are functions providing a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x = operator.iadd(x, y).Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.

  7. Python Assignment Operators

    In Python, an assignment operator is used to assign a value to a variable. The assignment operator is a single equals sign (=). Here is an example of using the assignment operator to assign a value to a variable: x = 5. In this example, the variable x is assigned the value 5. There are also several compound assignment operators in Python, which ...

  8. Python In-Place Assignment Operators

    Python provides the operator x *= y to multiply two objects in-place by calculating the product x * y and assigning the result to the first operands variable name x. You can set up the in-place multiplication behavior for your own class by overriding the magic "dunder" method __imul__ (self, other) in your class definition. >>> x = 2. >>> x ...

  9. PEP 572

    Unparenthesized assignment expressions are prohibited for the value of a keyword argument in a call. Example: foo(x = y := f(x)) # INVALID foo(x=(y := f(x))) # Valid, though probably confusing. This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

  10. 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 ...

  11. Python

    Python - Assignment Operators - 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. ... Augmented modulus operator with int and int a= 0 type(a): <class 'int'> Augmented modulus operator with int and float a= 4.5 type(a): <class 'float ...

  12. Operator Overloading in Python

    Operator Overloading in Python. Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because '+' operator is overloaded by int class and str class. You might have noticed that the ...

  13. Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity

    Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise. Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and ...

  14. Assignment Operators in Python:

    Python offers several compound assignment operators, which combine an operation with assignment. They provide a shortcut to perform an operation and update a variable in a single step. 1.Addition ...

  15. Python Assignment Operator Overloading

    Python - Assignment Operator Overloading Assignment operator is a binary operator which means it requires two operand to produce a new value. Following is the list of assignment operators and corresponding magic methods that can be overloaded in Python.

  16. Assignment Operator in Python

    The simple assignment operator is the most commonly used operator in Python. It is used to assign a value to a variable. The syntax for the simple assignment operator is: variable = value. Here, the value on the right-hand side of the equals sign is assigned to the variable on the left-hand side. For example.

  17. Every dunder method in Python

    For more on callability, see Callables: Python's "functions" are sometimes classes. Arithmetic operators . Python's dunder methods are often described as a tool for "operator overloading". Most of this "operator overloading" comes in the form of Python's various arithmetic operators. ... Python performs the operation followed by an assignment.

  18. Python Operators

    Assignment operators in Python are used to assign values to variables. These operators make the code more concise and improve its readability by combining arithmetic operations with assignment. The Basic Assignment Operator (=) The = operator assigns the value on the right to the variable on the left. x = 10 print(x) # Output: 10

  19. How to Change Class Attributes in Python

    Using Direct Assignment; Using setattr() function; Using Class method; Using a property decorator; Edit Class Attributes Using Direct Assignment. In this example, we use the direct assignment approach to edit the class attribute website of the Geeks class, initially set to " GeeksforGeeks ". After direct assignment, we print the original and edited values, printing the update to " GFG ".

  20. Custom assign operator for Python class

    Custom assign operator for Python class. I want to write a Python class that behaves/looks similar to win32com Excel cell assignment (need to wrap it). I want to have a comparable behaviour, i.e. ws.Cells (r,c).Value = x # win32com myws.setCell (r,c,v) # "classical" object method in Python myws (r,c).Value = x # what I want / need with my own ...