McLeodx McLeodx - 1 month ago 7
Python Question

Checking if something is true in all iterations of a Python for loop

I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using

continue
to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of that list.

The reason I'm asking is because with either the if statement being satisfied, or with none of the else iterations being satisfied, both situations see the same outcome, a continuation past this block.

for group in groups:
if point in group:
continue
else:

# if point not an element of any group,
create group in groups with variable as only element


Update:

Would this work? Is there a more succinct way to do it?

for group in groups:
if point in group:
groupCheck = 1
else:
pass
if not groupCheck:
# Create a new list including point

Answer

Reverse your logic, and use the else clause of the for loop to create the new group.

for group in groups:
  if point in group:
    break
else:
  create_new_group(point)

Or just use any().

if not any(point in group for group in groups):
  create_new_group(point)