What's the complexity of `+=` for a string in Python

55 Views Asked by At

Since it's immutable it should be O(n) however some optimisations are done under the hood (cf. other SO posts like this one https://stackoverflow.com/a/70499811/11092636).

However, since it's neither O(1) neither O(n) (source, the benchmark I just did below), what is the complexity? Are there official sources?

enter image description here

MRE to reproduce:

import time
import matplotlib.pyplot as plt

def average_time_to_append(length):
    total_time = 0
    for _ in range(20000):  # Repeat 20000 times
        test_string = 'a' * length
        start_time = time.time()
        test_string += 'a'
        end_time = time.time()
        total_time += end_time - start_time
    return total_time / 20000  # Return the average time taken

lengths = list(range(10, 5*10**5))

# Measure
times = [average_time_to_append(length) for length in lengths]

# Plot
plt.figure(figsize=(10, 6))
plt.plot(lengths, times, marker='o')
plt.xlabel('String Length')
plt.ylabel('Time to append (seconds)')
plt.title('Benchmark: Time to Append \'a\' to a String')
plt.grid(True, which="both", ls="--")
plt.savefig("test.png")
0

There are 0 best solutions below