2

It might be a basic question but what does line, = in the below code?

import numpy as np
import matplotlib.pyplot as plt

ax = plt.subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)

plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )

plt.ylim(-2,2)
plt.show()

I tried with a simple example a, = 1 which throws the error int object is not iterable, and this a, = 1, works.

So what does var, = does?

bhansa
  • 7,282
  • 3
  • 30
  • 55
  • I'm curious, what do you get from `print(line)` after `line, = plt.plot(t, s, lw=2)`. I can't test atm but I wasn't aware that `plot()` returned anything. – roganjosh Nov 18 '17 at 11:52
  • @roganjosh Full reference [adding text](https://matplotlib.org/users/pyplot_tutorial.html#annotating-text) – bhansa Nov 18 '17 at 11:53
  • @roganjosh it return a Line2D object `Line2D(_line0)` – bhansa Nov 18 '17 at 11:55

1 Answers1

2

The call to plt.plot(t, s, lw=2) returns a tuple with one element. This is then unpacked into a variable: line.

The same logic can be seen here:

>>> a = tuple([1])
>>> a
(1,)
>>> b, = a
>>> b
1
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54