Python - Compound Assignments and Sequence

Introduction

When applied to a sequence such as a string, the augmented form performs concatenation instead.

Demo

S = "test" 
S += "TEST"                 # Implied concatenation 
print( S )

Result

For augmented assignments, inplace operations is applied for mutable objects.

Demo

L = [1, 2] 
L = L + [3]                 # Concatenate: slower 
print( L )
L.append(4)                 # Faster, but in place 
print( L )

Result

And to add a set of items to the end, we can either concatenate again or call the list extend method:

Demo

L = [1, 2] 
L = L + [5, 6]              # Concatenate: slower 
print( L )
L.extend([7, 8])            # Faster, but in place 
print( L )

Result

Related Topic