0

I often encounter some pieces of python codes like the following:

l, = plt.plot(t, s, lw=2)

(The line above is borrowed from a widgets example from matplotlib itself)

I wanted to know what does the assignment l, = ... really mean?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
arash
  • 161
  • 13
  • 1
    `l, = something` is basically equivelant to `l = something[0]`. This is kind of a special case of *sequence unpacking* since the number of variables and number of elements in the sequence you're trying to assign are both 1. Compare with something like `l, m = [1, 2]`. I'm not a fan of this kind of syntax though since it doesn't make it clear that `plt.plot(t, s, lw=2)` is actually returning a tuple. This is also equally valid `[l] = plt.plot(t, s, lw=2)`. – eugenhu Apr 04 '18 at 10:06
  • @eugenhu please don't post answers in comments. Also: you are wrong: `plt.plot` returns a list, not a tuple, and `l, = foo()` is not equivalent to `l = foo()[0]` – FlyingTeller Apr 04 '18 at 10:18
  • @FlyingTeller I didn't feel like it was a complete answer (and I didn't really want to write one) but it gives enough of an explanation to be helpful. And yeah they're not the same, I didn't phrase that well but what I was trying to show was in this scenario they will achieve the same things. `l, = something` will fail if `something` is a sequence of more than one element. Also you're right that `plt.plot` returns a list, that's my mistake when I typed that, but my point was just I don't like this kind of `l, = ...` usage. – eugenhu Apr 04 '18 at 10:37

0 Answers0