-3
input_list = [22,456,3465,456,6543,546,345]
for num in input_list:
    if num==0 or num%2==0:
        input_list.remove(num)

Could you please tell me what is the problem in this code? It is not removing second 456 from the list.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
rock
  • 1

1 Answers1

0

The problem with your code is that you are removing an item while iterating over the list.

So when the num become 22 then 22 will be removed and 456 become index 0 in your list, in the next iteration the for loop looks for index 1 which is 3465.

Try this:

input_list = [i for i in input_list if i%2 == 1]
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • this is a very classic duplicate, you probably know it since you answered it very quickly. Please vote to close instead of answering. – Jean-François Fabre Apr 18 '19 at 10:52
  • @Jean-FrançoisFabre In the first part, I explained OP's problem. but you are the moderator. are you still prefer to close this? You are the master. – Mehrdad Pedramfar Apr 18 '19 at 10:54
  • You can vote to close as duplicate without being moderator. I did this with my gold python badge only. There's no moderator power involved here. – Jean-François Fabre Apr 18 '19 at 10:55
  • I know, but I thought the OP's problem is the problem of his code, not to achieve the goal. I will look more carefully. Thanks for your comment, You are one the best moderator, I voted for you ;) – Mehrdad Pedramfar Apr 18 '19 at 10:57