2

What is the "line," mean or do in python? I gather it has something to do with iterables in an object.

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()
bmorton12
  • 309
  • 1
  • 3
  • 10
  • You mean in the `plt.annotate` line ? It's just that the line breaks because it's too long. You could put everything in one line, sometimes it depends on your text editor. – Mel Aug 29 '15 at 12:24
  • @tmoreau On the 7th line there --> `line, = plt.plot(t, s, lw=2)` – Bhargav Rao Aug 29 '15 at 12:24
  • Oh sorry. I guess the functions returns a tuple, I'll investigate – Mel Aug 29 '15 at 12:25

2 Answers2

2

line, = plt.plot(t, s, lw=2) means that plt.plot returns a list or a tuple of one element, and you are extracting that element (which is assigned to line).

Chris Jester-Young
  • 213,251
  • 44
  • 377
  • 423
2

Python knows unpacking, to save a tuple, list or other iterable into separate variables:

a, b = 3, 4

If some function returns a iterable with only one element, there is also only one variable to unpack into:

line, = plt.plot(t, s, lw=2)
Daniel
  • 40,885
  • 4
  • 53
  • 79
  • Then there is really no point in putting the comma there because plt.plot(t, s, lw=2) only has one element, right? And, would there be a time where plt.plot(...) would return more than one element? Like plt.plot(t1, s1, t2, s2, lw=2) or something like that? – bmorton12 Aug 29 '15 at 12:43