Home > database >  Python Sublists Remove Method
Python Sublists Remove Method

Time:03-16

I have the following list of suubjects and grades I have named "gradebook"

gradebook list

I am attempting to remove the value 85 from the sublist [poetry, 85] sublist

I can remove the sublist itself with the following syntax

gradebook.remove(["poetry", 85])

I can't seem to remove the 85

I have tried to use the following syntax

gradebook.remove([85]) 

but I get the following error

> Traceback (most recent call last):   File "script.py", line 15, in
> <module>
>     gradebook.remove([85])  ValueError: list.remove(x): x not in list

I have also tried to use the following

gradebook.remove([2][1]) 

Instead I get the following error

Traceback (most recent call last): File "script.py", line 15, in gradebook.remove(2) IndexError: list index out of range

I don't know if it is possible to, but how can I remove that item (85) in the sublist?

CodePudding user response:

When dealing with multi-dimensional data you need to navigate to the item you want to operate on before submethods will work as you expect. Your data is a list of lists, so you need to let the program know you want to operate on a specific list within your data. Your data is below.

gradebook = [[“physics”, 98], [“calculus”, 97], [“poetry”, 85], [“history”, 88]]

Navigate to the item of index 2 so the returned value is the list ["poetry", 85]. Then you can operate on this list individually by calling the .remove(85) method.

# Define gradeboook
gradebook = [[“physics”, 98], [“calculus”, 97], [“poetry”, 85], [“history”, 88]]
# Get the index of your list
index = gradebook.index(["poetry", 85])
# Navigate and remove 85
gradebook[index].remove(85)

You can also do the last two steps with one line:

gradebook[gradebook.index(["poetry", 85])].remove(85)

This works because the item returned when you call gradebook[gradebook.index(["poetry", 85])] is the list ["poetry", 85] itself. Once you call it in this way you can modify it with remove(), as you please.

CodePudding user response:

So index starts at 0 for lists so you could just do del gradebook[1]

  • Related