0

Just started to learn how to code.I was trying to use remove() in for loop to remove the specific value if condition met but the result is what I expected

student = ["A", "B", "C"]
bad = input("who is absent?: ")
for i in student:
    if i in bad:
        student.remove(bad)
    else:
        print(i)

The result looks like this if I typed A in input

who is absent?: A
C

I was expecting the out to be something like

who is absent?: A
B C
TechoCat
  • 1
  • 1

2 Answers2

1

As a general rule, don't change the iterable that you are currently iterating over. It can often lead to unintended outcomes such as this. In this instance, what is happening is (not exactly but to give you an idea)

  1. It sees that "A" is in student ->The next in iterator is "B"
  2. It removes "A" from student -> The next in iterator is "C"
  3. It moves to next, which is "C" instead of "B"

In the event that you only need to print the remaining ones, don't remove "A". In the event that you do need to remove the items, refer to this post.

Shorn
  • 718
  • 2
  • 13
1

Remove method mutates the list so whenever you remove 'A' from the list, while iterating it causes problems, thats why you dont see 'B'.

In normal you expect for i in student: to work like: First, i = 'A', then i = 'B', then i ='C' but whenever you remove 'A' from the list it works like: i = 'A' then it skips B because of indexing then i = 'C'.

Therefore, when you want to use a function mutating a list or etc, you should keep a copy of it and iterate on it.

student = ["A", "B", "C"]
student_copy = student.copy()
bad = input("who is absent?: ")
for i in student_copy:
    if i in bad:
        student.remove(bad)
    else:
        print(i)
Ugur Yigit
  • 155
  • 7
  • Is it okay if I write it ``` student = ["A", "B", "C"] bad = input("who is absent?: ") for i in student: if i in bad: student.remove(bad) print(student) ``` though it seems like a different thing – TechoCat Mar 09 '23 at 09:05
  • if you write like that then it will work as following: first, i =='A' then it will remove 'A' from the student list and will print remaining 'B' and 'C'. Then again it will be in for loop and since 'B' is not in the student list anymore, i will equal to 'C'. Therefore it will print student list again and it will print 'B' and 'C' – Ugur Yigit Mar 09 '23 at 10:28