Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to List while Iterating

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)
like image 272
user2097818 Avatar asked Mar 02 '13 14:03

user2097818


2 Answers

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) 
like image 141
Abhijit Avatar answered Oct 04 '22 20:10

Abhijit


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.

like image 24
Martijn Pieters Avatar answered Oct 04 '22 20:10

Martijn Pieters