Inplace operator in python

Inplace operator | Set -1

In Python, "in-place" operators allow you to perform an operation and assign the result to a variable in a single step. These operators are a shorthand notation that simplify common operations.

Here's a tutorial on in-place operators in Python:

1. Basic Arithmetic In-place Operators

  • Addition (+=)

    x = 5 x += 3 # Equivalent to x = x + 3 print(x) # Outputs: 8 
  • Subtraction (-=)

    x = 5 x -= 3 # Equivalent to x = x - 3 print(x) # Outputs: 2 
  • Multiplication (*=)

    x = 5 x *= 3 # Equivalent to x = x * 3 print(x) # Outputs: 15 
  • Division (/=)

    x = 5 x /= 2 # Equivalent to x = x / 2 print(x) # Outputs: 2.5 
  • Floor Division (//=)

    x = 5 x //= 2 # Equivalent to x = x // 2 print(x) # Outputs: 2 
  • Modulus (%=)

    x = 5 x %= 3 # Equivalent to x = x % 3 print(x) # Outputs: 2 
  • Exponentiation (**=)

    x = 5 x **= 2 # Equivalent to x = x ** 2 print(x) # Outputs: 25 

2. Bitwise In-place Operators

These operators are used for manipulating individual bits of numbers:

  • Bitwise AND (&=)

    x = 5 # Binary: 101 x &= 3 # Binary: 011 print(x) # Outputs: 1 (Binary: 001) 
  • Bitwise OR (|=)

    x = 5 # Binary: 101 x |= 3 # Binary: 011 print(x) # Outputs: 7 (Binary: 111) 
  • Bitwise XOR (^=)

    x = 5 # Binary: 101 x ^= 3 # Binary: 011 print(x) # Outputs: 6 (Binary: 110) 
  • Left Shift (<<=)

    x = 5 # Binary: 101 x <<= 1 # Shift bits to the left by 1 print(x) # Outputs: 10 (Binary: 1010) 
  • Right Shift (>>=)

    x = 5 # Binary: 101 x >>= 1 # Shift bits to the right by 1 print(x) # Outputs: 2 (Binary: 010) 

3. Usage with Other Data Types

In-place operators can also be used with other data types like lists and strings:

  • List

    lst = [1, 2] lst += [3, 4] # Appends elements to the list print(lst) # Outputs: [1, 2, 3, 4] 
  • String

    s = "Hello" s += ", World!" # Concatenates strings print(s) # Outputs: "Hello, World!" 

Conclusion

In-place operators provide a convenient way to perform operations and update variables simultaneously. They make the code concise and easier to read. However, it's essential to understand the underlying operation to avoid potential pitfalls or bugs in the code.


More Tags

sqldatatypes embedded-linux bootstrap-grid text-editor azure-configuration asp.net-core-1.0 uml connection-timeout automake tablet

More Programming Guides

Other Guides

More Programming Examples