0

I want to remove every element from the list that has "KA" sub string but when i tried to do so, it was not working properly.

def removeKA(reg_list):
    for reg_no in reg_list:
        if "KA" in reg_no:
            reg_list.remove(reg_no)
            print(reg_no)

reg_list = ["KA09 3056","KA12 9098","MH10 6776","GJ01 7854","KL07 4332"]
removeKA(reg_list)

No error messages were encountered. But Output should be KA09 3056 KA12 9098

But instead of that i am getting output as KA09 3056

  • 2
    you shouldn't modify a list as you are iterating it, it causes the iteration to skip some elements (as they are "shifted left" after deletion of previous element) – Adam.Er8 Jul 04 '19 at 08:04
  • Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Yossi Jul 04 '19 at 08:07

2 Answers2

2

Just use comprehension:

def removeKA(reg_list):
    return [i for i in reg_list if 'KA' not in i]

reg_list = ["KA09 3056","KA12 9098","MH10 6776","GJ01 7854","KL07 4332"]
removeKA(reg_list)

['MH10 6776', 'GJ01 7854', 'KL07 4332']
zipa
  • 27,316
  • 6
  • 40
  • 58
0

It's happening because the you are printing reg_no and not the list. The element is getting removed from the list though. Although, this is not the correct way to do the same.

def removeKA(reg_list):
for reg_no in reg_list:
    if "KA" in reg_no:

        # The element is removed below
        reg_list.remove(reg_no)

        # But the value still exists inside reg_no
        print(reg_no)
Gambit1614
  • 8,547
  • 1
  • 25
  • 51