-1

suppose that I have a list "graph" initialised as follows.

graph = [[1, 2, 3], [2, 3, 4], [3, 5, 7]]

How would I then determine if 1 was in graph?

Is there a simpler, more optimized way than doing something like,

in_graph = False
for row in graph:
    if 1 in row:
        in_graph = True
        break

?

Thank you,

hob

bobhob314
  • 16
  • 1
  • 9

2 Answers2

1

Try

any(x in row for row in graph)

where x is the element you are looking for.

VHarisop
  • 2,816
  • 1
  • 14
  • 28
0

You can use any with a generator expression.

any(1 in g for g in graph)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895