Best and/or fastest way to create lists in python

前端 未结 4 1953
既然无缘
既然无缘 2020-11-29 00:31

In python, as far as I know, there are at least 3 to 4 ways to create and initialize lists of a given size:

Simple loop with append:

4条回答
  •  爱一瞬间的悲伤
    2020-11-29 01:11

    There is one more method which, while sounding weird, is handy in right curcumstances. If you need to produce the same list many times (initializing matrix for roguelike pathfinding and related stuff in my case), you can store a copy of the list in the tuple, then turn it to list when you need it. It is noticeably quicker than generating list via comprehensions and, unlike list multiplication, works with nested data structures.

    #  In class definition
    def __init__(self):
        self.l = [[1000 for x in range(1000)] for y in range(1000)]
        self.t = tuple(self.l)
    
    def some_method(self):
        self.l = list(self.t)
        self._do_fancy_computation()
        #  self.l is changed by this method
    
    #  Later in code:
    for a in range(10):
        obj.some_method()
    

    Voila, on every iteration you have a fresh copy of the same list in no time!

    Disclaimer:

    I do not have a slightest idea why is this so quick or whether it works anywhere outside CPython 3.4.

提交回复
热议问题