meaning of: line, =

Albert-Jan Roskam fomcl at yahoo.com
Wed Feb 4 09:38:31 EST 2015



----- Original Message -----

> From: Chris Angelico <rosuav at gmail.com>
> To: 
> Cc: "python-list at python.org" <python-list at python.org>
> Sent: Wednesday, February 4, 2015 3:24 PM
> Subject: Re: meaning of: line, =
> 
> 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.



I have also never seen this before, but perhaps this:

>>> f = lambda: [42]
>>> result, = f()
>>> result
42

... is slightly cleaner than this:
>>> result = f()[0]
>>> result
42



More information about the Python-list mailing list