In my code, I have two options:
One is to:
images = [...] images.reverse() while len(images) > 0: image = images.pop() # do something with the image based on timestamp
The other is:
images = [...] while len(images) > 0: image = images.pop(0) # do something with the image based on timestamp
Both should work. But I am wondering from efficiency perspective, which approach is better?
Edit
I feel like I am not making this question clear. So I will paste more code here. The thing I need to do is something like below:
def __init__(self, position, tantType=True): self.image = self.images.pop(0) timer.add(interval, lambda :self.update(), len(self.images) + 1) def update(self): if len(self.images) > 0: self.image = self.images.pop() else: self.active = False
So it actually poped in a timer. I feel like I can’t just handle that in a loop
Advertisement
Answer
Repeatedly removing items from the beginning of the list is particularly bad because all the remaining items have to be shifted by one position to the left, making this an overall O(n²) operation.
The workaround of reversing the list first is better, but still unnecessary, because you can just iterate over the list.
Simply use a for
loop, and if you need to, delete the contents of the list afterwards:
for image in images: # do something with image images.clear()
To iterate over the list one step at a time in one function call, you can convert the list to an iterator at the beginning, and then use the next()
function to advance the iteration. If the iterator is exhausted it will raise a StopIteration
exception:
def __init__(self, position, tantType=True): self.images = iter(images) self.image = next(self.images) timer.add(interval, lambda: self.update(), len(images) + 1) def update(self): try: self.image = next(self.images) except StopIteration: self.active = False