Iteration style

Abdullah Khaidar khaidarx at yahoo.com
Thu Sep 23 04:57:22 EDT 2004


Is there any iteration style we must use to get faster processing
time? I've tried with some style to concat number in list. But I still
don't know which one is the recommended style.

>>> def useListIteration():
	list = [str(element) for element in range(5)]
	result = ""
	for item in list:
		result += item
	return result

>>> def useNormalIteration():
	list = [str(element) for element in range(5)]
	result = ""
	for index in range(len(list)):
		result += list[index]
	return result

>>> def useJoin():
	list = [str(element) for element in range(5)]
	return "".join(list)

>>> useListIteration()
'01234'
>>> useNormalIteration()
'01234'
>>> useJoin()
'01234'
>>> def getTimer():
	from timeit import Timer
	t1 = Timer("useListIteration", "from __main__ import
useListIteration")
	t2 = Timer("useNormalIteration", "from __main__ import
useNormalIteration")
	t3 = Timer("useJoin", "from __main__ import useJoin")
	print "Using list iteration: ", min(t1.repeat())
	print "Using normal iteration: ", min(t2.repeat())
	print "Using join: " , min(t3.repeat())

	
>>> getTimer()
Using list iteration:  0.0700158819068
Using normal iteration:  0.0701589168456
Using join:  0.0685698880724
>>> getTimer()
Using list iteration:  0.070928567737
Using normal iteration:  0.0698613929983
Using join:  0.0693454056312
>>> getTimer()
Using list iteration:  0.0683511451874
Using normal iteration:  0.0698585993471
Using join:  0.0708022947051
>>>



More information about the Python-list mailing list