How to check if all elements of a list match a condition?

I have a list consisting of like 20000 lists. I use each list’s 3rd element as a flag. I want to do some operations on this list as long as at least one element’s flag is 0, it’s like:

my_list = [["a", "b", 0], ["c", "d", 0], ["e", "f", 0], .....]

In the beginning, all flags are 0. I use a while loop to check if at least one element’s flag is 0:

def check(list_):
    for item in list_:
        if item[2] == 0:
            return True
    return False

If check(my_list) returns True, then I continue working on my list:

while check(my_list):
    for item in my_list:
        if condition:
            item[2] = 1

Actually, I wanted to remove an element in my_list as I iterated over it, but I’m not allowed to remove items as I iterate over it.

Original my_list didn’t have flags:

my_list = [["a", "b"], ["c", "d"], ["e", "f"], .....]

Since I couldn’t remove elements as I iterated over it, I invented these flags. But the my_list contains many items, and while loop reads all of them at each for loop, and it consumes lots of time! Do you have any suggestions?

5 Answers

Leave a Comment