Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time and Space Complexity of list to str conversion in Python

Trying to find out what is the time complexity of casting to string

str([1,2,6,...,3,6])

Pretty sure it's O(1) Not sure how to verify.

Edit: about space complexity, That should not be linear to list size, thinking O(1) because string has max size.

like image 422
WebQube Avatar asked Oct 14 '25 23:10

WebQube


1 Answers

It's linear, because bigger lists need more time and memory to convert.

enter image description here

Graph generated using perfplot. Code, for reference:

import numpy as np
import perfplot 

perfplot.show(
    setup=lambda n: np.random.choice(100, n).tolist(),
    kernels=[
        lambda lst: [str(x) for x in lst],
        lambda lst: list(map(str, lst)),
    ],
    labels=['[str(x) for x in lst]', 'list(map(str, lst))'],
    n_range=[2**k for k in range(0, 20)],
    xlabel='N',
    logx=True,
    logy=True,
    equality_check=None)
like image 58
cs95 Avatar answered Oct 17 '25 13:10

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!