Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Sublists Remove Method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading