[Tutor] most efficient way to do this

Alan Gauld alan.gauld at btinternet.com
Fri Feb 15 01:48:56 CET 2008


"Christopher Spears" <cspears2002 at yahoo.com> wrote 

> from arrays import locations
> 
> add_on = "chris"
> new_loc = []
> 
> for i in range(len(locations)):
>    new_loc.append(locations[i] + add_on)
> 
> print new_loc
> 
> Is this the most efficient way to do this?  

No.
For a start you could use a direct for loop rather than 
the index method. But even better this is a standard 
list comprehension job:

add_on = 'chris'
new_loc = [item+add_on for item in locations]

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list