common problem - elegant solution sought

Bruno Desthuilliers bruno.42.desthuilliers at
Tue Jan 15 12:19:48 CET 2008

Helmut Jarausch a écrit :
> 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.

If you don't care about ordering, you could use a dict:

d = dict(L)
del d['b']
L = d.items()

But I guess you care about ordering !-)

Anyway, you can still use a dict to find out the date part:

d = dict(L)
t = ('b', d['b'])

Or you could build an 'index' list to find out the appropriate index:
index = [key for key, val in L]
pos = index.index('b')
del L[pos]

> My straight forward solution is a bit lengthy, e.g.
> L=[("a","070501"),("b","080115"),("c","071231")]
> pos=-1
> found=-1
> for (Key,Date) in L :
>     pos+= 1
>     if  Key == "b" :
>         found= pos
>         break
> if  found >= 0 :
>     del L[found]
> print L

You could have used the enumerate(seq) function here. And since you're 
breaking out once the element deleted, you could as well delete it from 
within the loop:

for pos, (key, date) in enumerate(L):
   if key == 'b':
     del L[pos]

Benchmarking left as an exercice to the reader !-)

Also note that the "best" solution may depend on your real use case and 

More information about the Python-list mailing list