+ 4
How to multiply two list in python.
I tried to multiply two lists by * operator but in gives error. Also plz tell me the answers to the following question aĀ = [1, 2, 3] b=[4, 5, 6] c= a*b d=c[0:3] e=d a[5]=10 c[1]=20 e[0] = 30 What will be the output of following statements? (i) print(e) (ii) print(a) (iii) print(d) (iv) print(c)
6 Answers
+ 5
Multiplying of lists is not supported in Python.
Also when you multiply 2 lists what do you do to them? Do you treat them like matrices or do you just multiply corresponding terms?
+ 5
You can use numpy library and function multiply:
import numpy as np
a = [[2, 2], [2, 2]]
b = [[1, 2], [3, 4]]
print(np.multiply(a, b)) # [[2, 4], [6, 8]]
+ 3
a=[[1,0,0],[0,1,0],[0,0,1]]
b=[[1,2,3],[4,5,6],[7,8,9]]
C=[ ]
for i in range(3):
C.append([ ])
for j in range(3):
C[i].append(0)
for x in range(3):
C[i] [j] +=a[i][x]*b[j][x]
print(C)
+ 1
c = list(zip(a, b))
d = []
for i in range(len(c)):
d.append(c[i][0] * c[i][1]
0
Prometheus I just want to multiply each corresponding term.
0
To multiply two lists of similar or different size, you can use the zip() function with list comprehension.
Here is the code:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
result = [num1*num2 for num1, num2 in zip(a,b)]
print('Multiplication result is: ', result)
This will take care of list multiplication irrespective of the size of the lists.
Here is the full article...
https://programmersportal.com/how-to-multiply-two-lists-in-JUMP_LINK__&&__python__&&__JUMP_LINK