Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a "better" code question
#1
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
?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
It should be the second one.
The first one creates a new object. I think.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
You could timeit.timeit() the two statements for comparison.
Reply
#5
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020