1

I am trying to build shopping cart using Python 3. I could remove item by item name but I tried to remove item by index while iterating through a cart with the below code.

def removeItem(index):
clear_output()
for index in range(len(cart)):
    try:
        cart.pop(index)
        #del cart[index]
        print('{} has been remove from cart.'.format(index))
    except:
        print('Sorry we could not remove that item.')

I add two items into the cart: bacon and egg. then I show the cart:

def showCart():
clear_output()
if cart:
    print('Here is your cart:')
    for item in cart:
        #print('- {}'.format(item))
        print(cart.index(item)+1, item) # show item with index
else:
    print('Your cart is empty.')

Then, I tried to remove an item from cart with its index (which begin with 1 as in showCart() function), however, it always removes the first item and the output:

0 has been remove from cart.
Sorry we could not remove that item.

please let me know if my question is not clear enough.

MikeB
  • 59
  • 1
  • 7
  • I looked it but I want to remove item by its index – MikeB Feb 10 '20 at 10:28
  • Could you provide a minimal working example maybe? What clear_output() does exactly? – kalzso Feb 10 '20 at 10:28
  • Hi kalzso, please refer to this link : https://www.programcreek.com/python/example/72307/IPython.display.clear_output – MikeB Feb 10 '20 at 10:34
  • @MikeB: no, no matter *how* you remove items, the underlying problem is the same: **changing a list while you are iterating over it**. You should not do that. Pure logic may help you understand it, but if not: for each `index` that you are looping over, print out its value *and* the entire cart contents. You will see the loop gets wonky after the very first `pop`. (By the way, isn't that why you *had* to add that `try`? Just to make it not error out? This is why it did that!) – Jongware Feb 10 '20 at 10:42

0 Answers0