I have a list that contains some stuff similar to the below entry:
[[1, 'Potato', 2, 'Bag'], [2, 'Banana, 1, 'Bunch']]
.
These elements represent in order the item's UPC, Name, Quantity, and unit type. What I want to do is delete all the items at a certain index to change the list from the above to [[1, 'Potato', 2, 'Bag']]
. I tried a couple of methods, but I either used them wrong or they weren't supposed to be used there (I used del, pop, and remove). How do I go about doing this?
Asked
Active
Viewed 293 times
-2

steelscape02
- 25
- 5
-
Did you try slicing? – sudden_appearance Feb 14 '22 at 20:25
-
How do I do that? – steelscape02 Feb 14 '22 at 20:26
-
3`del your_list[1]` should have worked here, can you show what you tried and the error you got / how it was different from your expected output? – shriakhilc Feb 14 '22 at 20:26
-
As would `your_list.pop(index)`. Please see [ask] and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre] – Pranav Hosangadi Feb 14 '22 at 20:27
-
`[start_index: last_index]` to an list. For example `[1, 2, 3, 4, 5][:3]` will produce `[1, 2, 3]` – sudden_appearance Feb 14 '22 at 20:27
-
oh that worked. I was using del wrong. Thank you! – steelscape02 Feb 14 '22 at 20:28
-
@EliHarold that makes no difference. `del lst[index]` removes that element, regardless of the type of the element – Pranav Hosangadi Feb 14 '22 at 20:29
-
I know. My page hadn't refreshed while I was typing that response. I'm responding to shriakhilc's comment. – steelscape02 Feb 14 '22 at 20:30
-
@PranavHosangadi yes I know that, I thought they wanted to remove items from sublists. – Eli Harold Feb 14 '22 at 20:31
-
It helps to show working code so we have variable names to reference. – tdelaney Feb 14 '22 at 20:31
-
Basically. My apologies for asking this question. I was using the del command incorrectly. – steelscape02 Feb 19 '22 at 13:49
1 Answers
1
del
works for your example
>>> data = [[1, 'Potato', 2, 'Bag'], [2, 'Banana', 1, 'Bunch']]
>>> del data[1]
>>> data
[[1, 'Potato', 2, 'Bag']]

tdelaney
- 73,364
- 6
- 83
- 116