1

Hey guys I am learning about matplotlib right now and linear functions. So I got this task at codecademy:

"We have provided a slope, m, and an intercept, b, that seems to describe the revenue data you have been given.

Create a new list, y, that has every element in months, multiplied by m and added to b.

A list comprehension is probably the easiest way to do this!"

So my solution looks like this (I am going to print the whole code in for simplicity):

import codecademylib3_seaborn
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
revenue = [52, 74, 79, 95, 115, 110, 129, 126, 147, 146, 156, 184]

#slope:
m = 10
#intercept:
b = 53

y = 0
for x in months:
  y += m*x + b

plt.plot(months, revenue, "o")
plt.plot(months, y)

plt.show()

Well, I have no Idea why but it doesnt work then if I want to plot y. So I looked up what they would do diffrent, and it looks like this. They changed y.

y = [m*x + b for x in months]

I have no idea why this works or how this works. I think not only the code looks awful, also the syntax can't be right. Can please someone explain this to me?

Trissi17g
  • 39
  • 6
  • 1
    That is a list comprehension (as the assignment suggests to use) and the syntax obviously is valid. What is so awful about it? What you have done is compute one single y value that is a sum of a lot of other y values and has no real meaning. What they do is calculate many y values which you then can actually plot, your value is basically just a single not really plotable point. – luk2302 Apr 10 '22 at 21:34

1 Answers1

2

First of all, the relevant portion of your code:

y = 0
for x in months:
  y += m*x + b

This is accumulating one value of y, not adding values to a list.

The list comprehension y = [m*x + b for x in months] is equivalent to:

y = []
for x in months:
    temp = m*x + b
    y.append(temp)

List comprehensions are a shorthand that make it easier to write this common kind of loop where you're creating a new list (y) based on the values in an existing list (months).

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880