Recently I noticed that the idiomatic python two-dimensional array initialisation is extremely slow. I am wondering, is there a good, proper way of doing this simple task fast? Also, are those two variants equivalent?
Here are some code snippets using timeit
import timeit
A = 5000
B = 7000
N = 10
def list_comprehension_xrange():
matrix = [[0 for j in xrange(A)] for i in xrange(B)]
def list_comprehension_range():
matrix = [[0 for j in range(A)] for i in range(B)]
def multiplication():
matrix = [[0] * A] * B
print "list_comprehension_xrange:", timeit.timeit(list_comprehension_xrange, number=N)
print "list_comprehension_range:", timeit.timeit(list_comprehension_range, number=N)
print "multiplication:", timeit.timeit(multiplication, number=N)
list_comprehension_xrange: 11.4952278137
list_comprehension_range: 13.5112810135
multiplication: 0.00100612640381
multiplication
case creates an outer list filled with 7000 references to a single list of 5000 items, rather than 7000 lists of 5000 items each, so its unsurprising that it is 3-4 orders of magnitude faster. \$\endgroup\$