Reputation: 31
Is there an easy way to remove the last character of a string in Python in O(1) time complexity? Would using string = string[:-1]
be O(1)?
Upvotes: 2
Views: 2035
Reputation: 213
# Stright-forward
example_string = 'some medium string for examining the timing of
different
truncate methodes'
example_string = example_string[:-1]
# Stright-forward explicit
example_string = 'some medium string for examining the timing of
different
truncate methodes'
example_string = example_string[0:len(example_string)-1]
# Deleting last char
example_string = 'some medium string for examining the timing of
different truncate methodes'
example_string = bytearray(example_string, encoding='utf-8')
del example_string[len(example_string)-1]
example_string = example_string.decode(encoding='utf-8')
# Creative way using replace (only valid if this word is unique in your string)
example_string = 'some medium string for examining the timing of different
truncate methodes'
example_string = example_string.replace('methodes', "methode")
>>> print(f'{timeit.timeit(stmt=test_code)}\tStright-forward')
0.03856031800387427 Stright-forward
>>> print(f'{timeit.timeit(stmt=test_code)}\tStright-forward explicit')
0.07093821599846706 Stright-forward explicit
>>> print(f'{timeit.timeit(stmt=test_code)}\tDeleting last char')
0.34045136597706005 Deleting last char
>>> print(f'{timeit.timeit(stmt=test_code)}\tCreative way using replace (only valid if this word is unique in your string)')
0.07177364896051586 Creative way using replace (only valid if this word is unique in your string)
Upvotes: 1
Reputation: 532023
No, because strings are immutable. The only thing you can do is create a modified copy of a str
value, which means copying all the characters you don't want to remove. Any such operation is inherently a O(n) operation.
string[:-1]
doesn't remove the last character; it copies all but the last character.
Upvotes: 5