Python Forum

Full Version: Multiply Lists of Lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a set of lists like this
[0.74, 0.91, 1.22, 0.91, 1.07, 1.07, 1.07, 1.07, 1.07, 0.74, 0.91, 0.91, 1.07, 1.07, 0.91, 1.07]
[1.23, 0.97, 2.09, 0.97, 0.83, 0.83, 0.83, 1.23, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83]
[1, 1.36, 1.83, 0.95, 1, 1, 0.95, 1.22, 0.95, 1, 0.67, 0.67, 0.95, 0.95, 1, 0.67]
[1.22, 1.07, 1.22, 0.65, 1.67, 0.65, 0.65, 1.32, 1.67, 1.67, 1.32, 0.65, 1.67, 1.67, 1.32, 1.67]
[1.1, 1.1, 1.1, 1.1, 1.1, 0.58, 1.1, 1.1, 1.1, 0.58, 1.1, 0.58, 0.58, 0.58, 1.1, 0.58]
[0.91, 0.91, 0.91, 0.91, 0.91, 0.7, 0.91, 0.91, 0.91, 0.91, 0.91, 0.91, 0.7, 0.7, 0.7, 0.7]
[0.72, 0.72, 0.72, 0.91, 0.88, 0.88, 0.88, 0.72, 0.91, 0.91, 0.45, 0.88, 0.91, 0.72, 1.25, 0.72]

Then what i have done is combine in to a list of lists
sumrate += [list1, list2, list3, list4, list5, list6, list7]

Then i can add each item from each list and multiply by 10.
multiplyrate = [10 * sum(i) for i in zip(*sumrate)]

But i am looking for a way to multiply each item rather than sum each item.
taking two lists of equal length:
>>> list1 = [0.74, 0.91, 1.22, 0.91, 1.07, 1.07, 1.07, 1.07, 1.07, 0.74, 0.91, 0.91, 1.07, 1.07, 0.91, 1.07]
>>> list2 = [1.23, 0.97, 2.09, 0.97, 0.83, 0.83, 0.83, 1.23, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83]
>>> result = [l1 * l2 for l1, l2 in zip(list1, list2)]
>>> print(result)
[0.9102, 0.8827, 2.5498, 0.8827, 0.8881, 0.8881, 0.8881, 1.3161, 0.8881, 0.6142, 0.7553, 0.7553, 0.8881, 0.8881, 0.7553, 0.8881]
cheers, i can work with that, thanks
When working with numbers, I would recommend to use Numpy, especially if you have millions of cells:

import numpy as np
list1 = [0.74, 0.91, 1.22, 0.91, 1.07, 1.07, 1.07, 1.07, 1.07, 0.74, 0.91, 0.91, 1.07, 1.07, 0.91, 1.07]
list2 = [1.23, 0.97, 2.09, 0.97, 0.83, 0.83, 0.83, 1.23, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83]
list1 = np.asarray(list1)
list2 = np.asarray(list2)
result = list1*list2
print(result)
Output:
[0.9102 0.8827 2.5498 0.8827 0.8881 0.8881 0.8881 1.3161 0.8881 0.6142 0.7553 0.7553 0.8881 0.8881 0.7553 0.8881]
I probably don't understand what you really want.

Not sure why you are using sum or zip if you just want to multiply each item in a list by a constant.

def multiply_each_element(alist, m):
    newlist = [alist[i] * m for i in range(len(alist))]
    return newlist

multiplied_list = multiply_each_element(l1, 10)
You get some weird values for some numbers. Something to do with how Python handles floats, I read about that somewhere.

You could pass 2 or more lists to a similar function and do some list tricks before multiplying. Probably need to find the shortest list first.
@Pedroski55 When you write for i in range(len(alist)), it often indicates that you should be writing for item in alist. In your case [item * m for item in alist] works very well.