Alter elements of a list

Summary Performance-wise, numpy or a list multiplication are clear winners, as they are 10-20x faster than other approaches.

I did some performance testing on the various options proposed. I used Python 2.5.2, on Linux (Ubuntu 8.10), with a 1.5 Ghz Pentium M.

Original:

python timeit.py -s 'bool_list = [True] * 1000' 'for x in xrange(len(bool_list)): bool_list[x] = False'

1000 loops, best of 3: 280 usec per loop

Slice-based replacement with a list comprehension:

python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False for element in bool_list]'

1000 loops, best of 3: 215 usec per loop

Slice-based replacement with a generator comprehension:

python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = (False for element in bool_list)'

1000 loops, best of 3: 265 usec per loop

Enumerate:

python timeit.py -s 'bool_list = [True] * 1000' 'for i, v in enumerate(bool_list): bool_list[i] = False'

1000 loops, best of 3: 385 usec per loop

Numpy:

python timeit.py -s 'import numpy' -s 'bool_list = numpy.zeros((1000,), dtype=numpy.bool)' 'bool_list[:] = False'

10000 loops, best of 3: 15.9 usec per loop

Slice-based replacement with list multiplication:

python timeit.py -s 'bool_list = [True] * 1000' 'bool_list[:] = [False] * len(bool_list)'

10000 loops, best of 3: 23.3 usec per loop

Reference replacement with list multiplication

 python timeit.py -s 'bool_list = [True] * 1000' 'bool_list = [False] * len(bool_list)'

10000 loops, best of 3: 11.3 usec per loop


If you only have one reference to the list, the following may be easier:

bool_list = [False] * len(bool_list)

This creates a new list populated with False elements.

See my answer to Python dictionary clear for a similar example.


Here's another version:

bool_list = [False for item in bool_list]