Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to initialize an integer array in python?

Say I wanted to create an array (NOT list) of 1,000,000 twos in python, like this:

array = [2, 2, 2, ...... , 2]

What would be a fast but simple way of doing it?

like image 990
Eddy Avatar asked Jul 09 '10 15:07

Eddy


1 Answers

The currently-accepted answer is NOT the fastest way using array.array; at least it's not the slowest -- compare these:

[source: johncatfish (quoting chauncey), Bartek]
python -m timeit -s"import array" "arr = array.array('i', (2 for i in range(0,1000000)))"
10 loops, best of 3: 543 msec per loop

[source: g.d.d.c]
python -m timeit -s"import array" "arr = array.array('i', [2] * 1000000)"
10 loops, best of 3: 141 msec per loop

python -m timeit -s"import array" "arr = array.array('i', [2]) * 1000000"
100 loops, best of 3: 15.7 msec per loop

That's a ratio of about 9 to 1 ...

like image 129
John Machin Avatar answered Oct 21 '22 04:10

John Machin