Consider the following code:
x = 'some string'
x = x[::-1]
Reversing a string is O(n). When we do x[::-1], I assume python is simply selecting the indexes of the string characters from last to first. He does that n times. (n = length of string). Therefore is it correct to say that "x = x[::-1]" is:
And without assignment ('x[::-1]') it is simply O(n) in time complexity and O(1) in space ?
It has O(n) for both time and space complexity. There are very few cases where Python optimizes away code. It will optimize if False:
code away, for example. But for something like this it won't.
Consider these two functions:
def foo1(x):
return x[::-1]
def foo2(x):
x[::-1]
Now look at the "disassembler" output for these two functions:
>>> dis.dis(foo1)
2 0 LOAD_FAST 0 (x)
2 LOAD_CONST 0 (None)
4 LOAD_CONST 0 (None)
6 LOAD_CONST 2 (-1)
8 BUILD_SLICE 3
10 BINARY_SUBSCR
12 RETURN_VALUE
>>>
>>> dis.dis(foo2)
2 0 LOAD_FAST 0 (x)
2 LOAD_CONST 0 (None)
4 LOAD_CONST 0 (None)
6 LOAD_CONST 2 (-1)
8 BUILD_SLICE 3
10 BINARY_SUBSCR
12 POP_TOP
14 LOAD_CONST 0 (None)
16 RETURN_VALUE
>>>
As you can see, they both include BUILD_SLICE
and BINARY_SUBSCR
. The only difference is that foo1
then does RETURN_VALUE
, while foo2
does POP_TOP
to discard the value, then LOAD_CONST
to load None
before doing RETURN_VALUE
.