Home > Enterprise >  Removing a specific index from a nested loop
Removing a specific index from a nested loop

Time:09-15

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]     

CodePudding user response:

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.

CodePudding user response:

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]]
  • Related