Python Forum

Full Version: a "better" code question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
part of code is going to work on a slice of a string, omitting the first character, such as handling an option. it needs to know the length of the part after the first character. which is the "better" way? this may be an issue of"pythonic" code.

getting the length of the actual slice:
    z = len(x[1:])
or subtracting 1 from the length of the original string:
    z = len(x)-1
?
It should be the second one.
The first one creates a new object. I think.
(Nov-17-2018, 03:49 AM)wavic Wrote: [ -> ]It should be the second one.
The first one creates a new object. I think.

It does, so it should be the second one.
You could timeit.timeit() the two statements for comparison.
Not only is a new object created, the first solution is O(n) where the first one is O(1), since all n references have to be copied into the new object.