pythonlisttuplesundirected-graph

Find a tuple in a list of tuples and add if not present


There is an undirected graph with a list of tuples where each element is a tuple in the form of (id1,id2). I have to find whether a new (s,t) is present in the list of tuples which contains all the edges and add the tuple if it is not present. edges is the list of tuples

def add_edge(s: str, t: str) -> None:
       
        if (s,t) or (t,s) not in edges:
            edges.append((s,t))
        return edges

But this fails in acoounting for duplicates of the form (a,b) = (b,a)


Solution

  • this will work well

    def add_edge(s: str, t: str) -> None:
           
            if (s,t) not in edge and (t,s) not in edges:
                edges.append((s,t))
            return edges