Omanba Forum

How do I remove items from a 2D list in Python?

Hello guys, I am writing a python code that will help organize sales data of a pizza joint. I am using a 2 Dimensional (2D) list for the project but having challenges deleting items from my list using the remove() method. Below is an excerpt of my code:

pizza_and_prices = [[2, "pepperoni"], [6, "pineapple"], [1, "cheese"], [3,"sausage"], [2, "olives"], [7, "anchovies"], [2, "mushrooms"]]

print(pizza_and_prices)

pizza_and_prices.sort()

print(pizza_and_prices)

cheapest_pizza = pizza_and_prices[0][1]

priciest_pizza = pizza_and_prices[-1][-1]

pizza_and_prices.remove([-1][-1])

This is the error message:

Traceback (most recent call last):
  File "script.py", line 18, in <module>
    pizza_and_prices.remove([-1][-1])
ValueError: list.remove(x): x not in list
2 Likes

My guess is that because -1 is not a valid index in the list you have

1 Like

Usually . remove() works when u indicate the item and not the index. Your code will work when u use pizza_and_prices.pop()
The pop() method removes the last item, or you can specify the index to remove it

2 Likes

I was expecting a response from @Reginald_Owusu for this question (I remember him as the Python guy :stuck_out_tongue:), but he was nowhere to be found. Welcome back Reginald. :slight_smile:

1 Like

Lol… I am still getting used to this forum. This is just my second time logging in. Hopefully I will be more regular
:sweat_smile::sweat_smile::sweat_smile:

2 Likes

Yeah, it can be a task for some people, the more you use it, the more you’ll get used to it (DUH? :stuck_out_tongue:). But seriously if you don’t get something please ask @Emp_Sel or @Danny, they are experts on how to use OF.

1 Like

Sure. Thanks. Will do that

Thanks for the help @Reginald_Owusu. It worked! :star_struck:

1 Like