-1

I am trying to multiply two arrays by using '@' but this is the error I get

a@b

unsupported operand type(s) for @: 'list' and 'list'

I read that '@' is used for matrix multiplication, which is what I need

1 Answers1

0

From the error message it appears as though you are using lists. You need to use arrays for which you can use the numpy module like this:

import numpy as np

x = [1,2,3,4]
y = [10,20,30,40]

x = np.array(x)
y = np.array(y)

z = x@y
print(z)

which returns this:

300

If you want to multiply lists without numpy you can do this:

# method 1
z = 0
for i, v in enumerate(x):
    z = z + (x[i]*y[i])
print(z)

# method 2
z = sum([x*y for x,y in zip(x,y)])
print(z)

Both would return the same value as above...

D.L
  • 4,339
  • 5
  • 22
  • 45
  • Beware that your method using `enumerate` may generate an `IndexError` if the lengths of the lists are not the same. – Chris Dec 14 '22 at 23:04
  • @Chris, yes, this would be true for all 3 methods (including `numpy` arrays). that would be a check that the user would need to do beforehand if they were at risk of that... `len(x) == len(y)`. – D.L Dec 14 '22 at 23:06
  • `zip` will not risk that. – Chris Dec 14 '22 at 23:30
  • @Chris, true, but the user then risks multiplying lists of different lengths accidentally without receiving an error (so a potential semantic error)... but point taken. – D.L Dec 14 '22 at 23:34
  • If you're on python3.10+, `zip(..., strict=True)` to avoid calculating dot product of incompatible vectors. – STerliakov Dec 15 '22 at 13:11