Home > Enterprise >  Working with values from 2 separate lists - Python
Working with values from 2 separate lists - Python

Time:11-28

I have 2 lists which each have 10 value and i want to multiply the values.

import random

n1_r = random.sample(range(1, 100), 10)
n2_r = random.sample(range(1, 100), 10)

n1 = n1_r
n2 = n2_r

for example I want to multiply the first value from n1 with the first value in n2 and so on?

im expecting a new list of 10 values stored in n3

CodePudding user response:

n3 = [a * b for a, b in zip(n1, n2)]

CodePudding user response:

You can do this in numerous ways. I would go with a basic list comprehension considering the experience level you are.

For example:

array1 = [2, 2, 2, 2]
array2 = [3, 3, 3, 3]
array3 = [i * j for i,j in zip(array1, array2)]
>>> array3
[6, 6, 6, 6]

Then you can always do some more succinct one liners too.

For example:

array3 = list(map(lambda x: x[0]*x[1], zip(array1, array2)))

There are many tools, modules, and constructs in python to accomplish this. Take a look at Pandas and the module operator for a couple of handy ways to process and operate data.

CodePudding user response:

There are multiple ways to do this. Refer https://www.entechin.com/how-to-multiply-two-lists-in-python/

For such advanced numerical operations you can use numpy library Eg:

import numpy as np

array1 = np.array(n1_r)
array2 = np.array(n2_r)
 
result = array1*array2
  • Related