igraph python check if vertex exist

Viewed 548

I need simple solution to check if vertex exists in big ebough graph

I tried find method, but I got ValueError if vertex is not in graph

For example that code will fail

def treeExample():
    g = Graph()
    g.add_vertex('a')
    g.add_vertex('b')
    g.vs.find(name = 'c')

if __name__ == '__main__':
    treeExample()

By fact I need some boolean function which just will tell if vertex exist or not (without runtime error or exception throwing)

Of course I could create my own set to check this but that's very inconvinient

So could the problem be solved around igraph library somehow ?

2 Answers

Try using select method:

g = Graph()
g.add_vertex('a')
g.add_vertex('b')
len(g.vs.select(name='c'))  # return 0
len(g.vs.select(name='a'))  # return 1

You can wrap find in a try- and except block. If the node exists, this will be faster than select for large graphs, as it will stop execution once a node is found.

def has_node(graph, name):
    try:
        graph.vs.find(name=name)
    except:
        return False
    return True
Related