Style in list comprehensions

Tim Peters tim.one at comcast.net
Fri Aug 15 15:41:18 EDT 2003


[Tim Lesher]
> 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,

Your Pythonic intuition needs refinement, then <wink>.  The first way is
obvious at first glance.  The second way builds a list for no apparent
reason, so is confusing on that count.  The first way is more Pythonic
because it's more obvious.  Note that the sheer number of lines of code has
nothing to do with Pythonicity, although *somtimes* the clearest way is also
the briefest way.

> but do I incur any overhead for creating the list of results when I'm
> not going to use it?

Of course, but avoiding overhead isn't the best reason for preferring the
first way.






More information about the Python-list mailing list