Home > Back-end >  I can't remove the item from the list by the type of the index
I can't remove the item from the list by the type of the index

Time:10-20

I don't know what to do, I want to remove the items from the list that are strings, but seems it does not work. Pls help me

lista1 = ["a","b","c","d"]
lista2 = [1,2,3,4]
lista1.extend(lista2)


for i in lista1:
    if type(i) == str:
        lista1.remove(i)

print(lista1)

CodePudding user response:

You shouldn't remove the items in the for loop. When you remove 'a' , the next index it checks is lista1[1]. Since 'a' is removed, lista1[1] is now 'c' instead of 'b'. It will skip 'b' because of this. One solution could be to make a copy of lista1 and remove items from that as it loops through the original.

CodePudding user response:

You can simply do the following:

lista1 = ["a","b","c","d"]
lista2 = [1,2,3,4]
lista1.extend(lista2)

non_string_list = list(filter(lambda x: not isinstance(x, str), lista1))
print(non_string_list)
  • Related