Efficiency of len() and pop() in Python

后端 未结 2 2027
野的像风
野的像风 2020-12-29 14:07

Why is this Significantly faster with comments? Shouldn\'t a pop, a comparison, and a length check be O(1)? Would that significantly affect the speed?

#! /us         


        
2条回答
  •  天命终不由人
    2020-12-29 14:41

    Just to answer part of the question: popping from the end (the right end) of a list takes constant time in CPython, but popping from the left end (.pop(0)) takes time proportional to the length of the list: all the elements in the_list[1:] are physically moved one position to the left.

    If you need to delete index position 0 frequently, much better to use an instance of collections.deque. Deques support efficient pushing and popping from both ends.

    BTW, when I run the program, I get a clean exception:

    ...
    length of pmarbs = 8306108
    Traceback (most recent call last):
      File "xxx.py", line 22, in 
        pmarbs.append(pot2)
    MemoryError
    

    That happened to be on a 32-bit Windows box. And it doesn't surprise me ;-)

提交回复
热议问题