meaning of: line, =

Chris Angelico rosuav at gmail.com
Wed Feb 4 09:24:52 EST 2015


On Thu, Feb 5, 2015 at 1:08 AM, ast <nomail at invalid.com> wrote:
> I dont understand why there is a comma just after line in the following
> command:
>
> line, = plt.plot(x, np.sin(x), '--', linewidth=2)
>
>
> I never saw that before
>
> Found here:
> http://matplotlib.org/examples/lines_bars_and_markers/line_demo_dash_control.html
>

That's a slightly unusual form of unpacking. Compare:

def get_values():
    return 5, 7, 2

x, y, z = get_values()

This is like "x = 5; y = 7; z = 2", because it unpacks the function's
return value into those three targets.

What you have is exactly the same, except that it has only one target.
So it's expecting plt.plot() to return an iterable with exactly one
thing in it, and it'll unpack it and put that thing into line:

def get_packaged_value():
    return [42]

x, = get_packaged_value()

This is equivalent to "x = 42". I don't know matplotlib, so I don't
know what it's returning or why, but as long as it's iterable and
yields exactly one thing, this will work.

ChrisA



More information about the Python-list mailing list