1

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' 
juanpa.arrivillaga
97.7k14 gold badges141 silver badges190 bronze badges
asked Feb 25, 2020 at 10:44
2
  • why are you trying to use lists like numpy arrays? Commented Feb 25, 2020 at 10:49
  • To me, it's not clear what you're asking. Do you want to use list like a numpy-array? (if so, why avoid numpy?) Or do you want to learn how to use numpy arrays? Commented Feb 25, 2020 at 10:52

5 Answers 5

4

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)]
answered Feb 25, 2020 at 10:48
Sign up to request clarification or add additional context in comments.

Comments

1

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)
answered Feb 25, 2020 at 10:51

Comments

0

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)
answered Feb 25, 2020 at 10:49

Comments

0

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
answered Feb 25, 2020 at 10:52

Comments

0

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]
answered Feb 25, 2020 at 11:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.