1

Is there any difference in initializing a list of lists by

  1. [[0 for i in xrange(n)] for j in xrange(m)]

or

  1. [[0]*n for j in xrange(m)]

From the point of view of time performance the first way is 4 times faster than the second way, and I am wondering whether the first way has any computational/memory use or allocation drawback.

sono
  • 266
  • 2
  • 7
  • 18
  • Hi @Ale. Not sure what you need this for, but maybe ask yourself if a `list` is the right data type. There's a chance that a `numpy.ndarray` is better for your application (https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.array.html). One of the reasons is the fact that lists are mutable, so you'll have to know what you're doing: https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types – Aleksander Lidtke Jun 26 '17 at 02:54
  • @AleksanderLidtke I am just focusing on numpy-free methods. Thanks, anyway. – sono Jun 26 '17 at 09:29

1 Answers1

1

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

First method is slower than the second method because a no-op is performed in each loop iteration.

P.S. If you want to initialise a list of list with constant value (k) then the ideal and the fastest way would be to used numpy np.ones((m, n))*k.