Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

TypeError: bad operand type for unary -: 'list' python

Writer Andrew Henderson

I Keep getting this error, It's so simple and error is about (-x) in function but I don't know how I can fix it. Please help me.

This is my code:

import numpy as np
x = list(np.arange(0, 1, 0.1))
print (x)
def f(x): f = np.exp(-x) return f
y =f(x)
print (y)
4

2 Answers

Broadcasting isn't supported for vanilla Python lists. You should use list() after the operation involving broadcasting, like so:

import numpy as np
x = np.arange(0, 1, 0.1)
print(x)
def f(x): f = np.exp(-x) return f
y = list(f(x))
print(y)
1

First of all, please use different names

import numpy as np
x = list(np.arange(0, 1, 0.1))
print (x)
def func(param): retval = np.exp(-param) return retval
y = func(x)
print (y)

for start.

Then, you make a list from the np.arange, python lists don't support the unary operation - (minus) as you are using in the function (i.e. f = np.exp(-x))

numpy arrays on the other hand do support it. what you can do is not convert it to python list, or only convert it to a python list later in the process (after using the minus)

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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