msicam
msicam

Reputation: 41

Python Calculation Using List

How can I perform calculations in python using two lists? Where the first calculation would be, c = -(1)/cos(4), second being, c = -(5)/cos(6), etc

import numpy as np
x, y = [1,5,2,1], [4,6,2,3]

c = []
c = -x/(np.cos(y))
print(c)

When I try this I currently get the error :

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

Upvotes: 1

Views: 242

Answers (5)

Kelly Bundy
Kelly Bundy

Reputation: 27589

The error tells you the problem: TypeError: bad operand type for unary -: 'list'

So you could just negate elsewhere (where you have a NumPy array):

c = -x/np.cos(y)     # Error
c = x/-np.cos(y)     # [ 1.52988566 -5.20740963  4.80599592  1.01010867]
c = -(x/np.cos(y))   # [ 1.52988566 -5.20740963  4.80599592  1.01010867]

Upvotes: 0

Naveenkumar
Naveenkumar

Reputation: 45

Hope ... there is no specific reason ... to handle as a list.

import numpy as np
x, y = [1,5,2,1],[4,6,2,3]
c = []
for k in range (len(x)):
    c = -x[k]/(np.cos(y[k]))
    print(c)

Result:
1.5298856564663974
-5.207409632975539
4.805995923444762
1.0101086659079939

Upvotes: 0

Mario Bonsembiante
Mario Bonsembiante

Reputation: 53

You have to cast the list to numpy array.

c = -np.array(x)/(np.cos(y))
print(c)

now you will have the results store in the np array

array([ 1.52988566, -5.20740963,  4.80599592,  1.01010867])

or if you want a list again

c = list(c)

Upvotes: 1

some_programmer
some_programmer

Reputation: 3528

You can iterate over the length of the list:

import numpy as np
x, y = [1,5,2,1], [4,6,2,3]

c = []
for i in range(0, len(x)):
    f = -x[i]/(np.cos(y[i]))
    c.append(f)
print(c)

Upvotes: 0

YamiOmar88
YamiOmar88

Reputation: 1476

This can be done without numpy:

from math import cos
x, y = [1,5,2,1], [4,6,2,3]
c = [-i/cos(j) for i,j in zip(x,y)]

Upvotes: 4

Related Questions