Python Forum
multiplying elements in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
multiplying elements in a list
#1
How do I multiply elements in a list with each other?

ex:
If I have to lists
[4, 0.8, 23]
[0.3, 2, 3]
How do I make these lists become a new list which should be [1.2, 1.6, 69]
Reply
#2
Hello,

you can try this:

a = [4, 0.8, 23]
b = [0.3, 2, 3]
c = list(map(lambda x: x[0] * x[1], zip(a, b)))
print(c)
Best Regards,

Nicolas TATARENKO
Reply
#3
Hi @Olavv
You can do this using numpy

Here is answer:
import numpy as np

input1 = np.array([4, 0.8, 23])
input2 = np.array([0.3, 2, 3])

result = input1*input2
print(result)
Reply
#4
Itertools & operator:
from itertools import starmap
from operator import mul

a = [4, 0.8, 23]
b = [0.3, 2, 3]

c = list(starmap(mul, zip(a, b)))
List comprehension:
a = [4, 0.8, 23]
b = [0.3, 2, 3]
c = [x * y for x, y in zip(a, b)]
With a for-loop and a list:
a = [4, 0.8, 23]
b = [0.3, 2, 3]

c = []
for x, y in zip(a, b):
    result = x * y
    c.append(result)
With a generator
from functools import reduce
from operator import mul


def mul_seq(*sequences):
    iterator = zip(*sequences)
    for multiplicators in iterator:
        yield reduce(mul, multiplicators)


a = [4, 0.8, 23]
b = [0.3, 2, 3]

c = list(mul_seq(a, b))

# or with more than two
d = list(mul_seq(a, b, c))
If you have big arrays, you should better use numpy, because this is optimized for matrix operation like broadcasting or matrix multiplication.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 373 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 427 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Checking if a string contains all or any elements of a list k1llcod3 1 1,023 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 1,900 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,013 May-17-2022, 11:38 AM
Last Post: Larz60+
  Why am I getting list elements < 0 ? Mark17 8 3,028 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 2,070 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Extracting Elements From A Website List knight2000 2 2,182 Jul-20-2021, 10:38 AM
Last Post: knight2000
  Make Groups with the List Elements quest 2 1,935 Jul-11-2021, 09:58 AM
Last Post: perfringo
  I cannot delete and the elements from the list quest 4 2,922 May-11-2021, 12:01 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020