So, I made some speed comparisons to get the fastest way. The list of concepts is really very fast. The only way to get closer is to avoid using bytecode while building the list. My first attempt was the following method, which, apparently, would be faster in principle:
l = [[]] for _ in range(n): l.extend(map(list,l))
(displays a list of length 2 ** n, of course) This construction is twice as slow as comprehending the list, according to timeit, for short and long (millions) lists.
My second attempt was to use starmap to call the list constructor for me. There is one construct that seems to launch the list constructor at maximum speed, but still slower, but only a tiny amount:
from itertools import starmap l = list(starmap(list,[()]*(1<<n)))
Interestingly, the runtime prompts that this is the final call to the list, which makes the starmap solution slow because its runtime is almost exactly equal to speed:
l = list([] for _ in range(1<<n))
My third attempt came when I realized that list (()) also creates a list, so I tried a simple simple:
l = list(map(list, [()]*(1<<n)))
but it was slower than calling starmap.
Conclusion: for speed maniacs: Use a list comprehension. Only calls if you need to. Use the built-in functions.
Jurjen Bos 08 Sep '15 at 7:18 2015-09-08 07:18
source share