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

1 comment :

  1. Hi, saw your blog on Proggit.

    Good post, but you didn't mention that the basis of your example, ie, list_obj=[i for i in range(0,10)], is called a "list comprehension".

    Also, using a simple range will lead to the same result as your example.

    >>> [i for i in range(0,10)]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(0,10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    Cheers, Bill