# Python homework

Hello there, I’d like to ask for some help with my python homework:

Define a list containing integer or float values. Define a python function called math_func solving a mathematic function (square or cubic by choice, i.e. y = x**2 + x + 5, where x is an input parameter and y is the returned value). Using list comprehension create a second list containing the results for calling math_func for each of the values in the first list. From the values in the two lists create and show a plot using pylab.

What do you need help with? We can help you, but won’t code the solution for you

I’ve written the first list with integers, the math_func and now I need help with the second list

are you going to share what you have so far?

Do i need to explain something about list comprehension? Have you tried writing a normal for loop and then trying to convert that to list comprehension?

import math

v = [1, 3, 7, 4, 8, 5]

def math_func(x):
y = x**2 + x + 5
return y

I tried something like this aswell but i think it doesn’t work:

list(math_func(x))

that is not list comprehension, this is:

``````a = [x for x in range(11)]
``````

its a comprehension to create a list. If i had to write the above code without the comprehension we would get:

``````a = []
for x in range(11):
a.append(x)
``````

the first `x` of the list comprehension is what you are append to list (`.append(x)` in the second example)

as you can see, list comprehension allows us to make a new list with less code. Have you tried to google:

python list comprehension

1 Like

Yeah, I’ve seen that example for list comprehension, but I just don’t know how to make it use the return from the math_func

you should have said that from the beginning. Making better questions will most likely result in getting better answers.

`return` is literally that, we can get values back from the function:

``````v = [1, 3, 7, 4, 8, 5]

def math_func(x):
y = x**2 + x + 5
return y

result = math_func(v)
print result # or print(result)
# depending on python version
``````

give the function hands back a value, we can use it in list comprehension to append values to list.

Oh yeah I see now, so how it’s going to look for all of the values of the list v, because i think for the homework i should use all of them, right?

I have to leave something for you to do, how do you think this could be achieved?

You could try to do this first:

``````a = []
for x in range(11):
a.append(x)
``````

and then convert the code to list comprehension.

this could me made by using any counter like i for example, to fill the list with all the elements of v

But as i try it doesn’t work

please show me what you tried, otherwise i have to guess what you tried which is really difficult i would loop over the list, to ensure you have all elements. And then append the result of calling `math_func` to list

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.