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?
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With