Thursday, August 27, 2009

Building Python Lists

Building primitive Python lists is a common task in virtually any Python application. The Python list is not unlike a traditional array in many respects, only more powerful. A common scenario is building a Python list from an iterator that yields values. In this case, each iteration adds a new element to the list being built. One method used to build Python lists using an iteration construct is the append method. This approach invokes the list append() method to append a new list element. Another approach to building Python lists is to place the iteration itself within the new list. This approach can be considered inline list building. The benefit to using the inline approach is the performance gain. The benefit to using the append method is readability when logic is required within each iteration that appends elements to the list. Below is an example illustrating both approaches.
#Example; Building Python lists.

import timeit

#Build a list consisting of ten elements using the append method.
def build_append():
for i in range(0,10):

#Build a list consisting of ten elements using the inline method.
def build_inline():
list_obj=[i for i in range(0,10)]

if __name__=="__main__":
#Setup timers.
"from __main__ import build_append")
"from __main__ import build_inline")

#Execute timers.

#Show results.
print "APPEND:",r_append
print "INLINE:",r_inline
print "DIFF %:",(r_inline/r_append)*100