is there a better way...

Cliff Wells logiplexsoftware at earthlink.net
Fri May 10 13:52:32 EDT 2002


On Fri, 10 May 2002 10:48:00 -0500
Mark McEahern wrote:

> [Christopher Encapera]
> > Subject: is there a better way...
> > to loop over a list and replace an element based on its value than:
> 
> There are three ways shown below, including your approach (replace).  Try
> the script and see for yourself how each performs:

Also see the additional method I've added here.

from time import clock
import random

### new function
def replace_index(l, old, new):
    # make a copy
    x = list(l)
    while 1:
        try:
            i = x.index(old)
            x[i] = new
        except ValueError:
            break
    return x

def replace(l, old, new):
    # Make a copy.
    x = list(l)
    y = len(x)
    z = 0
    while z < y:
        element = x[z]
        if element == old: x[z] = new
        z = z +1
    return x

def replace_for(l, old, new):
    # Make a copy.
    x = list(l)
    for i in range(len(x)):
        if x[i] == old:
            x[i] = new
            break # use continue if we expect more than one match.
    return x

def replace_dict(l, old, new):
    d = dict(zip(l, l))
    d[old] = new
    return d.values()

def timeit(f, *args):
    time_in = clock()
    result = f(*args)
    time_out = clock()
    return result, time_out - time_in

size = 100000
x = range(size)

old = random.randrange(0, size)
new = "blueberry"

r1, t1 = timeit(replace, x, old, new)
r2, t2 = timeit(replace_dict, x, old, new)
r3, t3 = timeit(replace_for, x, old, new)
r4, t4 = timeit(replace_index, x, old, new)

assert(r1==r2==r3==r4)
print "replace: %0.3f" % t1
print "replace_dict: %0.3f" % t2
print "replace_for: %0.3f" % t3
print "replace_index: %0.3f" % t4

#### Results:
replace: 0.180
replace_dict: 0.800
replace_for: 0.110
replace_index: 0.040

As has been commented upon before, exceptions are remarkably inexpensive in
Python.

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list