1

Can I iterate while simultaneous popping?

def process_shipments(shipments_list):
next_day_orders = []
bamboo_shoots = 20
bamboo_leaves = 15
for order in shipments_list:
    if order[1] < 20 and order[2] < 15 and bamboo_shoots > 0 and bamboo_leaves > 0:
        bamboo_shoots -= order[1]
        bamboo_leaves -= order[2]
        total_cost = ((5*order[1])+(2*order[2]))
        print (order[0], "-", "$",total_cost)
    else:
        next_day_orders += order
shipments_delete[:]
return next_day_orders

I'm asking if both versions are possible. I'm trying to optimize efficiency.

poke
  • 369,085
  • 72
  • 557
  • 602

2 Answers2

0

You are modifying shipments_list in a loop that is iterating over it. Don't do it as the loop indexing goes awry.

Paddy3118
  • 4,704
  • 27
  • 38
0

You're removing items from the list in the middle of your iteration. This almost always gives you strange results. By your comment, you just want shipments_list to be empty at the end, so do that at the end rather than in the middle of your loop:

for order in shipments_list:
    if order[1] <= 20 and order[2] <= 15 and bamboo_shoots >= 0 and bamboo_leaves >= 0:
        bamboo_shoots -= order[1]
        bamboo_leaves -= order[2]
        total_cost = ((5*order[1])+(2*order[2]))
        print (order[0], "-", "$",total_cost)
    else:
        next_day_orders += order

del shipments_list[:]   # <-- empty the list here
return next_day_orders

Why don't you want to remove items from the list in the loop? Consider this example:

>>> x = [0, 1, 2, 3, 4, 5]
>>> for y in x:
...     print y
...     x.remove(y)
...
0
2
4
>>>

Only even elements are iterated. The first element was 0. But in that loop, 0 was removed, so now the first element is 1. The next loop skips to the second element, which is now 2. 1 was never processed! So it is with 3 and 5 as well.

mhlester
  • 22,781
  • 10
  • 52
  • 75
  • I only did two things: I removed the `shipments_list.remove(order)`, and added `del shipments_list[:]`. I didn't (intentionally) change anything else. – mhlester Mar 01 '14 at 05:50