I need this behavior, but would rather have a diminishing list rather than a growing one. Sequence order is important for this operation.
for item in mylist:
if is_item_mature(item):
## Process him
else:
## Check again later
mylist.append(item)
but I would rather have it more like this. Does this behave like I think? Any better ways?
while mylist:
item = list.pop(0)
if is_item_mature(item):
##Process
else:
mylist.append(item)
The only problem I see with your approach is a growing list that depending upon your usage may eat up your memory
I would rather suggest you to use a Queue. Queue is designed and flexible enough to handle both ended production and consumption
from Queue import Queue
q = Queue() #You can also specify the maximum size of the Queue here
# Assume your Queue was filled
while not q.empty():
# It won;t block if there are no items to pop
item = q.get(block = False)
if is_item_mature(item):
#process
else:
#In case your Queue has a maxsize, consider making it non blocking
q.put(item)
You can safely append items to the list, and the iteration will include those items:
>>> lst = range(5)
>>> for i in lst:
... print i
... if i < 3:
... lst.append(i + 10)
...
0
1
2
3
4
10
11
12
However, if you prefer a diminishing list, then your while
loop is perfectly suitable for your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With