3

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
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
DanielSon
  • 1,415
  • 4
  • 27
  • 40
  • The question is, what are you doing after you identify it in a group? If nothing, just return after you find it. This really should be two functions: `find` and `add`. – GManNickG Oct 11 '16 at 00:25

4 Answers4

5

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)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

Why not just put the if statement outside of the loop?

found = False

for group in groups:
    if point in group:
        found = True
        break

if not found:
    groups.append([point])
eeScott
  • 143
  • 9
1

Make a function.

def check_matches(point, groups):
    for group in groups:
        if point in group:
            return true
    return false

if not check_matches(point, groups):
    groups.append([point])

You can leave it this simple, depending on what you are trying to do with this, or build this into a more sophisticated function:

def get_groups(point, groups):
    if not check_matches(point, groups):
        groups.append([point])
    return groups

groups = get_groups(point, groups)

There are simple list comprehension things you can do here, but given your apparent newness to Python I don't recommend them. It's a sure way to get you confused and to make more mistakes in the future.

enderland
  • 13,825
  • 17
  • 98
  • 152
1

Try using the built-in any() function.

if not any(point in group for group in groups):
    groups.append([point])
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135