Most efficient solution?

Terry Reedy tjreedy at home.com
Fri Jul 20 19:13:44 EDT 2001


<phawkins at connact.com> wrote in message
news:wkk813nz6e.fsf at mail.connact.com...
> >>>>> "TR" == Terry Reedy <tjreedy at home.com> writes:
>
> >> C = {}
> >> for item in B:
> >> C[item]=None
>
> TR> This sort of makes me wish we had dict comprehensions to match
list
> TR> comprehensions:
>
> TR> C = {item:None for item in B}
> TR> or
> TR> C = {item:1  for item in B}
> TR> as revised and then discarded
>
> So what's wrong with list comprehensions?  Observe, grasshopper:

Confucius say: People who make gratuitous snide putdowns set
themselves up to look like asses.

> Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
>
> import time
>
> a = [str(i) for i in range(7500)]
> b = [str(i) for i in range(0, 7500 * 5, 5)]
> c = {}
>
> for item in b:
> c[item] = 1
>
> def dict(a,c):
> start = time.clock()
> for item in a:
> d = filter(c.has_key, a)
> stend = time.clock()
> print "get: %6.2f"%(stend-start)
>
> def comp(a,b):
> start = time.clock()
> out = [i for i in a if i not in b]
> stend = time.clock()
> print "get: %6.2f"%(stend-start)

> >>> comp(a,b)
> get:  19.78
> >>> dict(a,c)
> get: 154.77

For years, people have compared reduce(), map(), and filter() to
equivalent contructs with for and if statements that do the same work
and produce the same result.  In the last year, such comparisons have
been extended to list comprehensions, which, last I knew, are
implemented by compiling them as if they had been written as some
equivalent set of nested for and if statements.  As I recall, most
such results have been fairly close (within say, a factor of two),
with details depending on the exact problem and platform (hardware +
operating system + compiler + compiler settings).  As a result, many
or most people have continued using whichever construct they prefer on
other grounds.

This mishmash of hashes producing 1500-element lists and
non-equivalent linear searches producing a 6000-element list says
*nothing* about anything 'wrong' with either list comprehensions or
the nested for and if statements they abbreviate.  And even proper
comparisions involving reduce, map, and filter would have nothing to
do with dictionary comprehensions since none of them produce
dictionaries.

If my 'wish' become strong enough, I will follow the proper procedure
for proposals and write a PEP so dict comprehensions either get added
or have a documented reason after discussion why not.

Terry J. Reedy





More information about the Python-list mailing list