Efficient Find and Replace

Scott David Daniels scott.daniels at acm.org
Sat Jan 28 12:19:39 EST 2006

Murali wrote:
 > Given: L = list of integers. X and Y are integers.
 > Problem: find every occurrence of X and replace with Y

 > Problem with both solutions is the efficiency.

As everyone else says, you are hallucinating efficiency problems
probably brought on by an overdose of Lisp or ML.  Here is another
way to get to what you want that will go "even faster" than the
not-a-problem speed you have from simple compare and replace.

     lst = range(50) * 10
         position = lst.index(X)
         while True:
             lst[position] = Y
             position = lst.index(X, position + 1)
     except ValueError:
         pass   # finally could not find X

I mention this only because people always seem to forget than index 
allows you to specify a start (and/or stop) position w/in the list.

--Scott David Daniels
scott.daniels at acm.org

More information about the Python-list mailing list