Efficient Find and Replace

Raymond Hettinger python at rcn.com
Sat Jan 28 06:03:52 CET 2006

[David Hirschfield]
> for i,v in enumerate(L):
>     if v == X:
>         L[i] = Y

Here's an alternate solution using a replacement dictionary:

  M = {X:Y}
  for i, v in enumerate(L):
      L[i] = M.get(v, v)

The replacement dictionary directly supports generalization to multiple
substitution pairs without needing additional passes over the input.
Also, if you feel the need for speed, the method lookup can be bound
outside of the loop:

  # Find/Replace multiple pairs in a single pass using a bound method
  M = {X1:Y1, X2:Y2, X3:Y3}
  Mget = M.get
  for i, v in enumerate(L): 
      L[i] = Mget(v, v)


More information about the Python-list mailing list