What is the time complexity of string slice? O(k) or O(n)

able-leopard :

Is the time complexity of python str slice O(k) or O(n)?

The answers I am reading suggest its O(k) but I don't understand how.

For example

my_str = "thisismystringfortesting"

sub_str = my_str[3:10]

I understand its extracting only (k) characters, but doesn't the operation have to convert the whole string into a list first before the slice? My thought process is that the conversion of the entire string into a list alone would cost O(n). Unless only part of the string gets converted into a list?

So can someone please explain is string slicing on Python O(k) or O(n)?

Thanks so much!

Jacques Gaudin :

The relevant code is here and it is O(k) as it can be seen line 1628

result_buf = PyBytes_AS_STRING(result);
for (cur = start, i = 0; i < slicelength;cur += step, i++) {
        result_buf[i] = source_buf[cur];
}
return result;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397612&siteId=1