# multiply each element of a list by a number

Colin J. Williams cjw at ncf.ca
Mon Dec 29 16:07:00 CET 2008

```skip at pobox.com wrote:
>>>>>> "Colin" == Colin J Williams <cjw at ncf.ca> writes:
>
>     Colin> skip at pobox.com wrote:
>
>     >> For extremely short lists, but not for much else:
>     >>
>     >> % for n in 1 10 100 1000 10000 100000 ; do
>     >> >   echo "len:" \$n
>     >> >   echo -n "numpy: "
>     >> >   python -m timeit -s 'import numpy ; a = numpy.array(range('\$n'))' 'a*3'
>     >> >   echo -n "list: "
>     >> >   python -m timeit -s 'a = range('\$n')' '[3*x for x in a]'
>     >> > done
>     >> len: 1
>     >> numpy: 100000 loops, best of 3: 11.7 usec per loop
>     >> list: 1000000 loops, best of 3: 0.698 usec per loop
>     >> len: 10
>     >> numpy: 100000 loops, best of 3: 11.7 usec per loop
>     >> list: 100000 loops, best of 3: 2.94 usec per loop
>     >> len: 100
>     >> numpy: 100000 loops, best of 3: 12.1 usec per loop
>     >> list: 10000 loops, best of 3: 24.4 usec per loop
>     >> len: 1000
>     >> numpy: 100000 loops, best of 3: 15 usec per loop
>     >> list: 1000 loops, best of 3: 224 usec per loop
>     >> len: 10000
>     >> numpy: 10000 loops, best of 3: 41 usec per loop
>     >> list: 100 loops, best of 3: 2.17 msec per loop
>     >> len: 100000
>     >> numpy: 1000 loops, best of 3: 301 usec per loop
>     >> list: 10 loops, best of 3: 22.2 msec per loop
>     >>
>     >> This is with Python 2.4.5 on Solaris 10.  YMMV.
>
>     Colin> Your comment is justified for len= 100
>     Colin> or 1,000 but not for len= 10,000 or 100,000.
>
> Look again at the time units per loop.
>
>     Colin> I wonder about the variability of the number of loops in your
>     Colin> data.
>
> That's how timeit works.  It runs a few iterations to see how many to run to
> get a reasonable runtime.

That's interesting but that's not the
way timeit is documented for Python 2.5:

timeit( [number=1000000])

Time number executions of the main
statement. This executes the setup
statement once, and then returns the
time it takes to execute the main
statement a number of times, measured in
seconds as a float. The argument is the
number of times through the loop,
defaulting to one million. The main
statement, the setup statement and the
timer function to be used are passed to
the constructor.

>
>     Colin> I have tried to repeat your test with the program below, but it
>     Colin> fails to cope with numpy.
>
> I stand by my assertion that numpy will be much faster than pure Python for
> all but very short lists.
>

In spite of the fact that your own data
doesn't support the assertion?

I would have expected numpy to be the
clear winner for len > 1,500.

Perhaps your data questions the value of
timeit as a timing tool.

Colin W.

```