[BangPypers] which one is the best pythonic way .
Anand Balachandran Pillai
abpillai at gmail.com
Tue Feb 9 07:48:14 CET 2010
On Tue, Feb 9, 2010 at 10:52 AM, Srinivas Reddy Thatiparthy <
srinivas_thatiparthy at akebonosoft.com> wrote:
>
> Thanks for the replies and I avoid using lambdas..
> Btw,Shall I avoid using filter and map ?
> Because what ever filter and map do,I could seem to do the same with
> Listcomprehensions..
> Is there any situation in which they fare better than list
> comprehensions?
>
map, filter, reduce at al are orders slower when compared to
list comprehensions, cuz each invocation of these cost one
function call, whereas list comprehensions are optimized in
the language.
For example,
>>> def f1(): [i for i in range(1000) if i % 3 == 0]
...
>>> def f2(): filter(lambda x: x%3==0, range(1000))
And using timeit,
>>> mytimeit.Timeit(f1, number=10000)
'211.47 usec/pass'
>>> mytimeit.Timeit(f2, number=10000)
'319.08 usec/pass'
The only advantage of map, filter etc over list comprehensions is
that they are sometimes concise over the equivalent list
comprehensions, when combined with already defined functions.
For example,
>>> [ x for x in range(1000) if (x%3==0) or (x%5==0)]
>>> def f(x): (x%3==) or (y %5==0)
>>> map(f, range(1000))
But again, keep in mind that these are much slower when compared
to the list comprehension or generator equivalent.
There are a few cases when a map function looks more "elegant"
when compared to the equivalent list comp.
For example, let us say you want to add together two lists.
>>> l1=range(5, 10)
>>> l2=range(10, 15)
>>> map(lambda x,y: x+y, l1, l2)
[15, 17, 19, 21, 23]
There is no direct way to do this in list comp except taking
the help of "zip".
>>> [a+b for a,b in zip(l1,l2)]
[15, 17, 19, 21, 23]
But practicality beats purity. Given a choice, I will always use the
latter instead of the former, irrespective of the "elegance", which
is questionable and subjective anyway :)
> Regards,
> ~ Srini T
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>
--
--Anand
More information about the BangPypers
mailing list