0

I need to multiply these two lists together but one is very long and the other is very short, the long list's length is a multiple of the short one's length. How can I multiply them in a way that the short one is repeated until all of the elements in the long list have been multiplied by it.

For example:

longList = [10, 10, 10, 10, 10, 10, 10, 10, 10] 
shortList = [1, 2, 3]

What I am trying to do:

longList * shortList # Something like this

Desired output

[10, 20, 30, 10, 20, 30, 10, 20, 30] 

*This is not a duplicate of How to zip two differently sized lists? because I am not looking to zip them, but rather to multiply them.

CypherX
  • 7,019
  • 3
  • 25
  • 37
Jacob Myer
  • 479
  • 5
  • 22
  • Possible duplicate of [How to zip two differently sized lists?](https://stackoverflow.com/questions/19686533/how-to-zip-two-differently-sized-lists) – walnut Oct 17 '19 at 00:11
  • I probably should have used integers in `longList`, I do in fact want to multiply the two lists instead of zipping them. @uneven_mark – Jacob Myer Oct 17 '19 at 00:13
  • 2
    Zipping is only the preparation. You must then use it in a list comprehension: `[a*b for a,b in zip_list]`. I assumed that this was not what you are asking about. – walnut Oct 17 '19 at 00:15
  • Is your question about zipping two lists of different lengths? – Dani Mesejo Oct 17 '19 at 00:28
  • @DanielMesejo I didn't think that it was but uneven_mark 's comment above answered my question – Jacob Myer Oct 17 '19 at 00:37

3 Answers3

3

You could achieve this with a simple loop and itertools

import itertools

longList = [1, 0, 2, 6, 3, 4, 5, 3, 1]
shortList = [1, 2, 3]

output_list = []

for long, short in zip(longList, itertools.cycle(shortList)):
    output_list.append(long * short)
Connor
  • 31
  • 2
0

Solution

The following code will work even if the number of elements in longList is not an exact multiple of shortList. And it does not require any import statements either.

longList = [10, 10, 10, 10, 10, 10, 10, 10, 10,] 
shortList = [1, 2, 3]

container = list()
n = len(longList)%len(shortList)
m = int(len(longList)/len(shortList))
for _ in range(m):
    container += shortList.copy()     
if n>0:
    container += shortList[:n]
[e*f for e,f in zip(container, longList)]

Output:

[10, 20, 30, 10, 20, 30, 10, 20, 30]
CypherX
  • 7,019
  • 3
  • 25
  • 37
0

The following pythonic function (using a list comprehension) should work:

def loop_multiply(ll,sl) : 
    return [ x*sl[i%len(sl)] for i,x in enumerate(ll) ] 


print(loop_multiply([10,10,10,10,10,10,10,10,10],[1,2,3])) 
# prints - [10, 20, 30, 10, 20, 30, 10, 20, 30]

Hope that helps :)

Sheun Aluko
  • 124
  • 6