shouldn't list comprehension be faster than for loops?

Carlos Grohmann carlos.grohmann at gmail.com
Thu Dec 17 12:37:58 EST 2009


Hello all

I am testing my code with list comprehensions against for loops.

the loop:

    dipList=[float(val[1]) for val in datalist]
    dip1=[]
    for dp in dipList:
        if dp == 90:
            dip1.append(dp - 0.01)
        else:
            dip1.append(dp)

listcomp:

    dipList=[float(val[1]) for val in datalist]
    dip1=[(dp, dp-0.01)[dp==90.0] for dp in dipList]


Tenting the time spent by each approach (using time.clock()), with a
file with about 100,000 entries, I get 0.03s for the loop and 0.05s
for the listcomp.

thoughts?

TIA
Carlos




More information about the Python-list mailing list