How to control the creation of an instance?

7stud bbxx789_05ss at yahoo.com
Sun Jun 3 01:26:56 EDT 2007


I just noticed that in your code you used pop(0).  It's not efficient
to pop an element off the front of a list because after doing so,
every other element in the list has to be moved over to the left one
position.  If you pop() an element off the end of the list, then the
first element in the list remains the first element, and the 2nd
element remains the 2nd element, etc., so no shifting of the remaining
elements is required.  If you need to pop elements of the front of a
list, then it's more efficient to use a deque, which can be found in
the collections module.  Here is an example:

import collections

class A(object):
    pass

def getObj(a_deque):
    if a_deque:
        return a_deque.popleft()
    else:
        return A()

x = collections.deque([A(), A()])
print x

newlist = []
for i in range(0,3):
    newlist.append(getObj(x) )

print newlist

--output:--
deque([<__main__.A object at 0x55d90>, <__main__.A object at
0x55db0>])
[<__main__.A object at 0x55d90>, <__main__.A object at 0x55db0>,
<__main__.A object at 0x55e30>]




More information about the Python-list mailing list