Style in list comprehensions

Dave Kuhlman dkuhlman at rexx.com
Fri Aug 15 16:58:03 EDT 2003


Tim Lesher wrote:

> Suppose I have a list of objects and I want to call a method on
> each. I can do the simple:
> 
> for i in objs:
>     i.meth(arg1, arg2)
> 
> or using list comprehensions:
> 
> [i.meth(arg1, arg2) for i in objs]
> 
> The second feels more Pythonic, but do I incur any overhead for
> creating the list of results when I'm not going to use it?
> 

Play fair.  Your two scripts do not do the same thing.  The script
using list comprehension forms a list containing each of the
results of applying meth to the items in the original list.  If you
do not need the resulting list, then use the for-loop.  If you do
need that list, then to make the two lists equivalent, you might
modify the for-loop as follows:

    result = []
    for i in objs:
        result.append(i.meth(arg1, arg2))

Now ask which is preferred.

The script using list comprehension has the advantage of of
possibly mystifying Perl programmers. They do enough of that to us
Pythonista's, so it serves them right, don't you agree.

Come to think about it, if you think it might mystify anyone, then
it is un-Pythonic to write it that way.

As to speed, my eyeballs could detect no difference with the
following:

    def func1(x):
        return x*3
    def t1(lst):
        return [func1(x) for x in lst]
    def t2(lst):
        result = []
        for x in lst:
            result.append(func1(x))
        return result
    a = t1(range(100000))
    a = t2(range(100000))

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dkuhlman at rexx.com




More information about the Python-list mailing list