Using += in a loop
Yigal Duppen
yduppen at xs4all.nl
Tue Jul 30 15:12:32 EDT 2002
> I am using the following code structure in some very long (10's of
> thousands of iterations) loops.
> Is there a more efficient way that doesn't use +=?
> Would s5 = '%s,"%s"' % (s5,x[1]) be better?
>
> t = ()
> s5 = ''
> for i in range(0,5):
> q = breaks[brk][i]
> x = mkup(cost*q,list*q)
> if x[0]: t+=(x[0]/q,)
> else: t+=(0,)
> if x[1]: s5+=',"'+x[1]+'"'
> else: s5+=',"-"'
> t += (0,0)
> s5 += ',"-","-"'
Without exactly understanding what it does, here are some tips:
1) make t a list; this allows you to use 'append'. This is much faster since
append works on an existing list. <tuple> += <tuple> creates a new tuple
every time. <list> += <list> is quite efficient as well
2) make s a list as well, append all the strings you need, and join them in
the end.
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.
YDD
--
.sigmentation fault
More information about the Python-list
mailing list