2

I am attempting to store multiple function values in an array, in order to graph a function in python.

For the example, let's define that the function is y= x^2 and the argument values wanted are 1,2 and 3. The code I attempted is the following :

def ExampleFunction (x):
        return x**2
ArgumentValues=range(3)       
FunctionValues=ExampleFunction(ArgumentValues)

Unfortunately running the code results in an error:

TypeError: unsupported operand type(s) for ** or pow(): 'range' and 'int'

How can I return many function values into a string/array in python? As a result I would want the "function values" take the following form:

1,4,9

3 Answers 3

2

Use a list comprehension:

results = [ExampleFunction(x) for x in range(3)]
Sign up to request clarification or add additional context in comments.

Comments

1

This code answer :

def ExampleFunction (x):
    list_fn = []
    for item in x :
        list_fn.append(item**2)
    return list_fn 
ArgumentValues=range(3)       
FunctionValues=ExampleFunction(ArgumentValues)

Or this code :

def ExampleFunction (x):
    return x**2
ArgumentValues=range(3)   
FunctionValues= [ExampleFunction(x) for x in ArgumentValues]

1 Comment

You are still returning only 1 value with your function.
1

This is the perfect usage for map.

map(lambda x: x**2, range(3))
# [0, 1, 4]

In Python 3.X, map will return a map object instead of a list, so if you want to reuse it, you need to explicitly convert it to a list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.