Python: fastest way to create a list of n lists

前端 未结 5 638
温柔的废话
温柔的废话 2020-11-28 20:37

So I was wondering how to best create a list of blank lists:

[[],[],[]...]

Because of how Python works with lists in memory, this doesn\'t

5条回答
  •  清歌不尽
    2020-11-28 21:31

    The list comprehensions actually are implemented more efficiently than explicit looping (see the dis output for example functions) and the map way has to invoke an ophaque callable object on every iteration, which incurs considerable overhead overhead.

    Regardless, [[] for _dummy in xrange(n)] is the right way to do it and none of the tiny (if existent at all) speed differences between various other ways should matter. Unless of course you spend most of your time doing this - but in that case, you should work on your algorithms instead. How often do you create these lists?

提交回复
热议问题