The latter is said to have a slightly better performance when the list is large.
A test was then made:
Import Timedef Time_cost (func): def _time_cost (*args,**kw): t1=time.time () func (*args,**kw) t2= Time.time () return t2-t1 return _time_cost@time_costdef test_add (list_a,huge_list_b): return list_a+ Huge_list_b@time_costdef test_extend (list_a,huge_list_b): return List_a.extend (huge_list_b) if __name__== ' __ main__ ': print '-----big list test-------------' a=[1]*1000 b=[' a ']* (10**8) print ' Add cost:%s Seconds '%test_add (A, b) print ' Extend cost:%s seconds '%test_extend (A, b) print '-----small list Test-------------' a=[1]*1000 b=[' a ']* (10**2) print ' Add cost:%s seconds '%test_add (A, b) print ' Extend cost:%s seconds '%test_extend (A, B)
My machine is win7,64bit,6g memory, i3 CPU, the result is as follows:
-----Big list Test-------------add cost:1.30500006676 secondsextend cost:0.591000080109 seconds-----Small List Test-------------Add cost:0.0 secondsextend cost:0.0 seconds
When B is 10^8 length, extend consumes almost half the time it takes to operate.
At the 1000-length level, the difference is small. Almost the same.
+ = equals to extend, as follows:
Import Timedef Time_cost (func): def _time_cost (*args,**kw): t1=time.time () func (*args,**kw) t2= Time.time () return t2-t1 return _time_cost@time_costdef test_add (list_a,huge_list_b): List_a+=huge_ List_b return list_a@time_costdef test_extend (list_a,huge_list_b): return List_a.extend (huge_list_b) if __ name__== ' __main__ ': print '-----big list test-------------' a=[1]*1000 b=[' a ']* (10**8) a2=[1]* Print ' + = cost:%s seconds '%test_add (A, b) print ' Extend cost:%s seconds '%test_extend (a2,b)
Output:
-----Big list Test-------------+ = cost:0.506999969482 secondsextend cost:0.510999917984 seconds
Python list's +, + =, and extend operations