0

I need to build a function that takes a list and removes every item that doesn't meet all the criteria's I've specified.

The structure is the following :

def function(my_list):

    for element in my_list:
        if not criteria_1:
            my_list.remove(element)

        else:
            if not criteria_2:
                my_list.remove(element)

    return my_list
  • The issue is that the list I get as a result contains elements that don't match the criteria's
  • The expected output is a list that contains only elements that match all the criteria's.
Jakub Szlaur
  • 1,852
  • 10
  • 39
Madal
  • 17
  • 4

1 Answers1

0
  • You can make a one big if - it is more readable (i think at least)
  • You are deleting and iterating simultaneously which is incorrect - you need to create temporary list

This code should work:

def function(my_list):
    tmp = list(my_list)
    
    for element in my_list:
        if not (criteria1 and criteria2 and criteria3):
            tmp.remove(element)

    return tmp
Jakub Szlaur
  • 1,852
  • 10
  • 39
  • 1
    I wouldn't create a copy of the list and then remove data from it. I would create a new list with just the elements I need. Then the whole body of the function boils down to `return [element for element in my_list if criteria1 and criteria2 and criteria3]`. – Matthias Nov 03 '21 at 10:28
  • Yea you're right. Didn't think of it when I was creating the answer :) – Jakub Szlaur Nov 03 '21 at 10:31