-2

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]     
Henry
  • 1
  • 1
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Ocaso Protal Sep 15 '22 at 06:52

3 Answers3

1

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.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • What if e.g. `'Bob'` is twice in the list? – Ocaso Protal Sep 15 '22 at 06:53
  • That's beyond the scope of this question. I'd use a list comprehension anyway. – AKX Sep 15 '22 at 06:58
  • @AKX Can you show an example of a list comprehension suitable for an original list with 100 million elements? – DarkKnight Sep 15 '22 at 07:14
  • @Vlad No, I can't. I'd use a list comprehension for _this_, not 100 million items. My comment on your (pre-revision) answer wasn't to disparage it, just to note that listcomps take a copy. – AKX Sep 15 '22 at 07:18
1

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]]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • (Unless the list is e.g. 100 million entries long and you don't want to copy it.) – AKX Sep 15 '22 at 07:12
  • The revised answer does not necessarily work correctly, since it doesn't take into account that the list indices change when you delete items. – AKX Sep 15 '22 at 07:19
  • @AKX I think it does work because it deletes from high to low indices. Perhaps you could show an example where this would not work – DarkKnight Sep 15 '22 at 07:20
  • Oh, right, I didn't notice the `reversed()`. My bad :) – AKX Sep 15 '22 at 07:27
0

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]]
SergFSM
  • 1,419
  • 1
  • 4
  • 7