2

In the following implementation of a graph, what does the v, w = e assignment do and how does it work? I thought we are not allowed to do an asymmetrical assignment like that.

class Graph(dict):
    def __init__(self, vs=[], es=[]):
        """create a new graph.  (vs) is a list of vertices;
        (es) is a list of edges."""
        for v in vs:
            self.add_vertex(v)

        for e in es:
            self.add_edge(e)

    def add_vertex(self, v):
        """add (v) to the graph"""
        self[v] = {}

    def add_edge(self, e):
        """add (e) to the graph by adding an entry in both directions.

        If there is already an edge connecting these Vertices, the
        new edge replaces it.
        """
        v, w = e
        self[v][w] = e
        self[w][v] = e
1
  • It's called "unpacking" - a, b = [1, 2] for instance Commented Feb 22, 2013 at 21:07

2 Answers 2

4

The way it works is like this: e is actually a tuple, consisting of two elements. Stating v, w = e is equal to assigning the first element of e to v and the second to w.

As a demonstration, check the following python console output:

>>> e = (1, 2)
>>> u, v = e
>>> u
1 
>>> v
2

Hope that clears it up somewhat.

Sign up to request clarification or add additional context in comments.

Comments

0

It is because Allan Downey (book) wants to show you unpacking on the next page in his book.

Here he writes:

class Edge(tuple):
    def __new__(cls, *vs):
        return tuple.__new__(cls, vs)

    def __repr__(self):
        return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1]))

    __str__ = __repr__

...so it becomes explicit that it's a tuple.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.