Search code examples
pythonlistmultiplication

Multiplication of numbers in a list (Python)


Is there any function in Python which could multiply numbers in a list with each other?

input -> A = [1,2,3,4]

output -> B = [1*1, 1*2, 1*3, 1*4, 2*2, 2*3, 2*4, 3*3, 3*4, 4*4]

Or can someone help me with creating my own function? I've got over 8000 records and I wouldn't like to do it manually.

So far the only thing I came up with is:

for i in list:
    list[i] * list[i+1]

But I know that it wouldn't work and I got no idea how to process this data.


Solution

  • Here's an alternative way using combinations_with_replacement() from itertools:

    >>> A = [1,2,3,4]
    >>> from itertools import combinations_with_replacement
    >>> [a * b for a, b in combinations_with_replacement(A, 2)]
    [1, 2, 3, 4, 4, 6, 8, 9, 12, 16]