# Benchmark [was Re: common problem - elegant solution sought]

Helmut Jarausch jarausch at skynet.be
Tue Jan 15 16:09:17 CET 2008

```Again, many thanks to all who provide their solution.
I have timed these (though on my old P3(0.9GHz)) - see below
Helmut.

Helmut Jarausch wrote:
> Hi,
>
> I'm looking for an elegant solution of the following tiny but common
> problem.
>
> I have a list of tuples  (Unique_ID,Date) both of which are strings.
> I want to delete the tuple (element) with a given Unique_ID, but
> I don't known the corresponding Date.
>

#!/usr/bin/python

import random
import timeit

Lorg=[]

def genList(L) :
for f in range(ord('A'),ord('z')+1) :
for s in range(ord('A'),ord('z')+1) :
L.append((chr(f)+chr(s),str(random.randrange(0,1000000))))

genList(Lorg)
Times= 1000
T0= timeit.Timer('L=list(Lorg)','from __main__ import Lorg').timeit(Times)
print T0

SetUp1=r'''from __main__ import Lorg
def del_by_key(L,key) :
d= dict(L)
del d[key]
L[:]= d.items()
'''

SetUp2=r'''from __main__ import Lorg
def del_by_key(L,key) :
d= dict(L)
t= (key,d[key])
L.remove(t)
'''

SetUp3=r'''from __main__ import Lorg
def del_by_key(L,key) :
index= [k for k,val in L]
pos  = index.index(key)
del L[pos]
'''

SetUp4=r'''from __main__ import Lorg
def del_by_key(L,key) :
for pos, (k,d) in enumerate(L):
if  k == key :
del L[pos]
break
'''

SetUp5=r'''from __main__ import Lorg
def del_by_key(L,key) :
L[:]= [(k,d) for (k,d) in L if k !=key]
'''

SetUp6=r'''from __main__ import Lorg
class Tester(object) :
def __init__(self,key) :
self.key= key
def __eq__(self,other) :
return other[0] == self.key

def del_by_key(L,key) :
del L[L.index(Tester(key))]
'''

print '*** ready ***'

T= timeit.Timer("L=list(Lorg);del_by_key(L,'Zz')",SetUp1).timeit(Times)
print "Method 1 :",T-T0

T= timeit.Timer("L=list(Lorg);del_by_key(L,'Zz')",SetUp2).timeit(Times)
print "Method 2 :",T-T0

T= timeit.Timer("L=list(Lorg);del_by_key(L,'Zz')",SetUp3).timeit(Times)
print "Method 3 :",T-T0

T= timeit.Timer("L=list(Lorg);del_by_key(L,'Zz')",SetUp4).timeit(Times)
print "Method 4 :",T-T0

T= timeit.Timer("L=list(Lorg);del_by_key(L,'Zz')",SetUp5).timeit(Times)
print "Method 5 :",T-T0

T= timeit.Timer("L=list(Lorg);del_by_key(L,'Zz')",SetUp6).timeit(Times)
print "Method 6 :",T-T0

# Results on an old P3 (0.9 GHz)
# *** ready ***
# Method 1 : 10.9850928783
# Method 2 : 5.96455168724
# Method 3 : 3.97821164131
# Method 4 : 1.66151881218
# Method 5 : 8.90886187553
# Method 6 : 6.2503888607

The clear winner is

def del_by_key(L,key) :
for pos, (k,d) in enumerate(L):
if  k == key :
del L[pos]
break

--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany

```

More information about the Python-list mailing list