[Tutor] Which way is better?

Alan Gauld alan.gauld at yahoo.co.uk
Fri Oct 23 19:12:56 EDT 2020


On 23/10/2020 20:14, Chris C wrote:

> the 2nd method? Which way is faster/better?

Those two terms are often result in contradictory answers.
But in this case not so...

> The purpose of the following code is to turn a string, such as
> '-4353,2339'into 2 int(),  by splitting the raw string into two, 

> for n in range(len(raw_string)):
>     if raw_string[n] == ',':
>         first_part = raw_string[0:n]
>         second_part = raw_string[n+1:]

> # Or this?
> 
> raw_string = raw_string.split(',')

The second.
Reasons?
1) It's shorter and easier to type
2) It's more readable - the meaning is in the name - split
3) It's faster because the library code is in C.
4) The compiler will tell you if you spell it wrong
5) It works. (the for loop breaks if there is no comma in the string!)

The first one isn't even a good Python version.
It iterates over the string when you could use
the find() method to locate the ',' and slice based
on that. Any time you write a for loop in Python
that iterates over range(len(x)) you should think
again and check for a better solution, there usually
is one to be found.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list