How do I multiply lists together using a function?
Asked Answered
H

6

2

how do I multiply lists together in python using a function? This is what I have:

    list = [1, 2, 3, 4]
    def list_multiplication(list, value):
         mylist = []
         for item in list:
              for place in value:
               mylist.append(item*value)
    return mylist

So I want to use this to multiply list*list (1*1, 2*2, 3*3, 4*4)

So the output would be 1, 4, 9, and 16. How would I do this in python where the 2nd list could be anything? Thanks

Humor answered 26/9, 2013 at 0:21 Comment(1)
The problem with the original code is that it iterates the inner list (value) once for each iteration of the outer list (list). While there are many approaches below, the fundamental key to this is "iterating two lists in step".Sphalerite
C
9

My favorite way is mapping the mul operator over the two lists:

from operator import mul

mul(2, 5)
#>>> 10

mul(3, 6)
#>>> 18

map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
#>>> <map object at 0x7fc424916f50>

map, at least in Python 3, returns a generator. Hence if you want a list you should cast it to one:

list(map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10]))
#>>> [6, 14, 24, 36, 50]

But by then it might make more sense to use a list comprehension over the zip'd lists.

[a*b for a, b in zip([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])]
#>>> [6, 14, 24, 36, 50]

To explain the last one, zip([a,b,c], [x,y,z]) gives (a generator that generates) [(a,x),(b,y),(c,z)].

The for a, b in "unpacks" each (m,n) pair into the variables a and b, and a*b multiplies them.

Colan answered 26/9, 2013 at 0:25 Comment(0)
T
4

You can use a list comprehension:

>>> t = [1, 2, 3, 4]
>>> [i**2 for i in t]
[1, 4, 9, 16]

Note that 1*1, 2*2, etc is the same as squaring the number.


If you need to multiply two lists, consider zip():

>>> L1 = [1, 2, 3, 4]
>>> L2 = [1, 2, 3, 4]
>>> [i*j for i, j in zip(L1, L2)]
[1, 4, 9, 16]
Thrice answered 26/9, 2013 at 0:22 Comment(1)
I know, but how would I do it with another list? So the list I provided above multiplied by another list? Say I do the list above times the list of list2 = [2,5,6,3]Humor
S
0

If you have two lists A and B of the same length, easiest is to zip them:

>>> A = [1, 2, 3, 4]
>>> B = [5, 6, 7, 8]
>>> [a*b for a, b in zip(A, B)]
[5, 12, 21, 32]

Take a look at zip on its own to understand how that works:

>>> zip(A, B)
[(1, 5), (2, 6), (3, 7), (4, 8)]
Spadework answered 26/9, 2013 at 0:25 Comment(5)
Is there anyway to do it without zip? That works good, but I'm just curious. ThanksHumor
Sure, there are countless ways to do it ;-) For example, [A[i]*B[i] for i in range(len(A))]Spadework
@Humor Did you not see my post? I covered a way 25 minutes before you asked. Also see izip's equivalent implementation from the docs for a way to do this manually without indexing.Colan
@TimPeters can you elaborate a little more on that other example? How would it fit into a function and for loop?Humor
@user2817437, sorry, I can't guess what you're asking for. How about editing your question, to summarize exactly what you're looking for: input, output, and what you've tried that still doesn't get you what you want.Spadework
S
0

zip() would do:

[a*b for a,b in zip(lista,listb)]
Sieracki answered 26/9, 2013 at 0:42 Comment(0)
C
0

zip is probably the way to go, as suggested by the other answers. That said, here's an alternative beginner approach.

# create data
size = 20
a = [i+1 for i in range(size)]
b = [val*2 for val in a]

a
>> [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20] 
b
>> [ 2  4  6  8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40] 

def multiply_list_elems(list_one, list_two):
    """ non-efficient method """
    res = [] # initialize empty list to append results
    if len(a) == len(b): # check that both lists have same number of elems (and idxs)
        print("\n list one: \n", list_one, "\n list two: \n", list_two, "\n")
        for idx in range(len(a)): # for each chronological element of a
            res.append(a[idx] * b[idx]) # multiply the ith a and ith b for all i
    return res

def efficient_multiplier(list_one, list_two):
    """ efficient method """
    return [a[idx] * b[idx] for idx in range(len(a)) if len(a) == len(b)]

print(multiply_list_elems(a, b))
print(efficient_multiplier(a, b))

both give:

>> [2, 8, 18, 32, 50, 72, 98, 128, 162, 200, 242, 288, 338, 392, 450, 512, 578, 648, 722, 800]

Yet another approach is using numpy, as suggested here.

Carvajal answered 17/6, 2017 at 4:48 Comment(0)
C
0

Use numpy for this.

>>> import numpy as np
>>> list = [1,2,3,4]
>>> np.multiply(list, list)
array([ 1,  4,  9, 16])

If you prefer python lists:

>>> np.multiply(list, list).tolist()
[1, 4, 9, 16]

additionally, this also works for element-wise multiplication with a scalar.

>>> np.multiply(list, 2)
array([2, 4, 6, 8])
Chinkapin answered 19/5, 2020 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.