Skip to content

Shorthand Operators

Augmented Assignment

1. Arithmetic

Operator Equivalent Description
+= x = x + y Add and assign
-= x = x - y Subtract
*= x = x * y Multiply
/= x = x / y Divide
//= x = x // y Floor divide
%= x = x % y Modulus
**= x = x ** y Power

2. Bitwise

Operator Equivalent Description
&= x = x & y Bitwise AND
\|= x = x \| y Bitwise OR
^= x = x ^ y Bitwise XOR
>>= x = x >> y Right shift
<<= x = x << y Left shift

Immutable Types

1. Integers

i = 9
print(f"{id(i) = }")

i = i + 3
print(f"{i = }")      # i = 12
print(f"{id(i) = }")  # Different ID

# vs shorthand
i = 9
original_id = id(i)
i += 3
print(f"{i = }")      # i = 12
print(f"{id(i) != original_id = }")  # True

2. Strings

s = "hello"
original_id = id(s)

s = s + " world"
print(f"{id(s) != original_id = }")  # True

# Shorthand also creates new
s = "hello"
original_id = id(s)
s += " world"
print(f"{id(s) != original_id = }")  # True

Mutable Types

1. Lists In-Place

lst = [1, 2, 3]
original_id = id(lst)

# += modifies in-place
lst += [4, 5]
print(f"{lst = }")  # lst = [1, 2, 3, 4, 5]
print(f"{id(lst) == original_id = }")  # True

2. Lists New Object

lst = [1, 2, 3]
original_id = id(lst)

# + creates new list
lst = lst + [4, 5]
print(f"{lst = }")  # lst = [1, 2, 3, 4, 5]
print(f"{id(lst) != original_id = }")  # True

Behavior Summary

1. Immutable

For int, str, tuple:

x = 10
# Both create new objects
x = x + 1   # New object
x += 1      # New object

2. Mutable

For list, dict, set:

x = [1, 2]
x += [3]      # In-place (same object)
x = x + [3]   # New object

Practical Examples

1. Counter Pattern

count = 0
for i in range(10):
    count += 1
print(f"{count = }")  # count = 10

2. Accumulator

total = 0
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    total += num
print(f"{total = }")  # total = 15

3. String Building

# Inefficient
result = ""
for i in range(5):
    result += str(i)
print(result)  # "01234"

# Better: use join
result = "".join(str(i) for i in range(5))
print(result)  # "01234"

Special Cases

1. List Extend

# These are equivalent
lst = [1, 2, 3]
lst += [4, 5]  # Calls __iadd__
# Same as: lst.extend([4, 5])

2. Set Operations

s = {1, 2, 3}
s |= {3, 4, 5}  # Union
print(s)  # {1, 2, 3, 4, 5}

s &= {3, 4}  # Intersection
print(s)  # {3, 4}

3. Dictionary Update

d = {'a': 1}
d |= {'b': 2}  # Python 3.9+
print(d)  # {'a': 1, 'b': 2}

Performance Notes

1. In-Place Faster

# Faster for large lists
big_list = list(range(1000000))
big_list += [1000000]  # In-place

# Slower (creates new)
big_list = big_list + [1000000]

2. String Concat

# Slow for many iterations
s = ""
for i in range(1000):
    s += str(i)  # 1000 objects

# Fast
s = "".join(str(i) for i in range(1000))