Removing a specific index from a nested loop

Viewed 35

I am trying to remove an index from the nested list but I am getting an error. The error is "TypeError: list indices must be integers or slices, not list". How can I delete indexes in this nested loop?

    student = [['Alice', 90], ['Bob', 80], ['Chad', 70]]
    sname = input("Student Name?")
    for i in student:
        if i[0] == sname:
            del student[i]     
3 Answers

You'll need enumerate() if you want to loop over the indexes as well as the list items. You can also unpack the (name, score) pairs in the same go:

student = [['Alice', 90], ['Bob', 80], ['Chad', 70]]
sname = input("Student Name?")
for i, (name, score) in enumerate(student):
    if name == sname:
        del student[i]
        break

Do remember it's generally not a good idea to modify a thing you're iterating over, and it can lead to very surprising results.

Note the indexes of the elements that need to be deleted. You can then del those elements but you need to do it in reverse order (for obvious reasons)

students = [['Alice', 90], ['Bob', 80], ['Alice', 85], ['Chad', 70]]

name = input('Enter name to delete: ')

for i in reversed([i for i, (n, _) in enumerate(students) if n == name]):
    del students[i]

print(students)

Terminal:

Enter name to delete: Alice
[['Bob', 80], ['Chad', 70]]

or you can just use filter function:

student = [['Alice', 90], ['Bob', 80], ['Chad', 70]]
sname = input("Student Name?")

list(filter(lambda x: x[0]!=sname, student))

>>> out
# Student Name?Bob
# [['Alice', 90], ['Chad', 70]]
Related