0

I am trying to solve a problem but this piece of code is providing invalid results. I want to remove all entries having values less than 10. Despite all my efforts, I could not understand that why it was not working well.

lis = [1,2,3,4,5,6,7,8,9,10,1,12,11,1,354,54,53,31,66,41,664,464,6468,46,461,61,65165,1651,56,6516,1]

for i in lis:
    if i<10:
        lis.remove(i)
print(lis)

I am getting the following output:

[2, 4, 6, 8, 10, 12, 11, 354, 54, 53, 31, 66, 41, 664, 464, 6468, 46, 461, 61, 65165, 1651, 56, 6516, 1]
  • Read the accepted answer in the linked duplicate for a good explanation, basically, when you remove an item from a list while you are iterating over it, it *skips* the next item in the iteration – juanpa.arrivillaga Jul 26 '21 at 05:17
  • Don't remove from list while iterating over it – kuro Jul 26 '21 at 05:17

1 Answers1

0

You can try with the following code:

lis = [1,2,3,4,5,6,7,8,9,10,1,12,11,1,354,54,53,31,66,41,664,464,6468,46,461,61,65165,1651,56,6516,1]
new_lis = [x for x in lis if x > 10]
GabrielP
  • 777
  • 4
  • 8