meaning of: line, =

Rustom Mody rustompmody at gmail.com
Wed Feb 4 10:09:54 EST 2015


On Wednesday, February 4, 2015 at 8:14:29 PM UTC+5:30, Albert-Jan Roskam wrote:
> ----- Original Message -----
> 
> > From: Chris Angelico 
> > Sent: Wednesday, February 4, 2015 3:24 PM
> > Subject: Re: meaning of: line, =
> > 
> > On Thu, Feb 5, 2015 at 1:08 AM, ast 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

Well its cryptic and confusing (to me at least)
And is helped by adding 2 characters:

(result,) = f()

instead of 

result, = f()




More information about the Python-list mailing list