Search code examples
pythonstringconcatenation

String concatenation in python takes exponential memory using different methods


s="hello"
l=[]
for i in range (1,7):
    for j in range(0,int(i)):
        s=s+s
    print(len(s.encode('utf-8')))

OUTPUT

10
40
320
5120
163840
10485760
s="hello"
l=[]
for i in range (1,7):
    for j in range(0,int(i)):
        l.append(s)
    s1=''.join(l)
    print(len(s1.encode('utf-8')))

OUTPUT

5
15
30
50
75
105

The first method concatenation takes exponential memory as compared to the second method can anyone please explain why? The codes are based on method 1 and method 4 shown on this website https://waymoot.org/home/python_string/


Solution

  • In the former, you're making your string exponentially big and bigger. Each time your code runs s=s+s, it makes it twice bigger. 5, 10, 20, 40, 80, and so on. More precisely, 5+5, then 10+10+20, ....

    BTW, in the latter, everytime you are just adding a hello string with length of 5 to the list. I strongly suggest you to print them out to see the content of s and s1.