User Tools

Site Tools


Replace for/while loops with list comprehension


Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it. If the expression would evaluate to a tuple, it must be parenthesized

This is a small script who exemplifies how easy a for loop can be replaced to obtain a clean, very pythonic stylish code. ;)
for i in numbers…. ⇒ [i for i in numbers if i % 5 == 0]

#!/usr/bin/env python2.6
# -*- coding: utf8 -*-
from timeit import Timer
def simple_for_loop():
    ''' This is the classical approach to the for loop'''
    numbers = range(1,10000000)
    i = 0
    result = []
    for i in numbers:
        if i % 5 == 0:
def list_comprehension():
    ''' List comprehension '''
    numbers = range(1,1000000)
    [i for i in numbers if i % 5 == 0]
print "Running the classical loop..."
t = Timer("simple_for_loop()", "from __main__ import simple_for_loop")
print "Done in %0.4f sec " % t.timeit(1)
print "Running with list comprehension..."
t = Timer("list_comprehension()", "from __main__ import list_comprehension")
print "Done in %0.4f sec " % t.timeit(1)

Running with different values for the given range number, I got:

Range 0-1000 0-10000 0-100000 0-1000000
Classical 0.0008 0.0789 0.2072 1.4278
List Com 0.0009 0.0736 0.1867 0.6863

Another fine example is this (using enumerate):

seq = ["one", "two", "three"]
def _dosomething(pos, elem):
    print "Elem %s at pos %s" % (elem, pos)
[_dosomething(i, e) for i, e in enumerate(seq)]

python/listcomprehension.txt · Last modified: 2013/03/16 17:40 (external edit)