Using += in a loop
Duncan Booth
duncan at NOSPAMrcp.co.uk
Wed Jul 31 05:06:02 EDT 2002
Yigal Duppen <yduppen at xs4all.nl> wrote in
news:3d46e4d4$0$94903$e4fe514c at dreader3.news.xs4all.nl:
> Something like this should be faster:
>
> t_list = []
> s5_list = []
> for i in range(0, 5):
> q = breaks[break][i]
> x = mkup(cost * q, list * q)
> if x[0]:
> t_list.append(x[0]/q)
> else:
> t_list.append(0)
>
> if x[1]:
> s5_list += [ ',"' , x[1] , '"']
> else:
> s5_list.append(',"-"')
> t_list += (0, 0)
> s5_list.append(',"-","-"')
>
> # and convert both lists to the desired types
> t = tuple(t_list)
> s5 = "".join(s5_list)
>
>
> No clue how much faster; that's what profile is for.
A few other suggestions that might or might not help:
I'm assuming the real code is inside a function, if not put it there at
once (that will speed it up a lot).
If mkup is simply returning two values, then use tuple unpacking to assign
the results directly into two variables instead of indexing. This allows
you to give the results meaningful names.
If the first result of mkup is always numeric, then you can collapse the if
statement down to a single append.
Optimise out the references to the append method from inside the loop.
Avoid using range in a for loop. 'i' isn't needed here at all.
All of which together (apart from the function) give you something like:
t_list, s5_list = [], []
t_append, s_append = t_list.append, s5_list.append
for q in breaks[break]:
numeric, stringval = mkup(cost * q, list * q)
t_append(numeric and numeric/q)
s_append(',"%s"' % stringval or "-")
t_list += (0, 0)
s_append(',"-","-"')
# and convert both lists to the desired types
t = tuple(t_list)
s5 = "".join(s5_list)
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list