Style in list comprehensions

Tim Peters at
Fri Aug 15 21:41:18 CEST 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