-4

Hello I am trying to learn list comprehension in python but can not find a way to multiply list elements together. Is it possible using list comprehension?

For example:

list=[1,2,3,4]

output should be an integer of the multiplication as in:

answer= 1*2*3*4
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
user2893825
  • 95
  • 2
  • 9
  • 3
    Please explain **multiply list elements together** with sample input and output. – Ahsanul Haque Nov 14 '15 at 20:12
  • Related: http://stackoverflow.com/questions/595374/whats-the-python-function-like-sum-but-for-multiplication-prod – Berci Nov 14 '15 at 20:27
  • 7
    List comprehensions are for building lists. You're not trying to build a list, so list comprehensions aren't a good tool for the job. – user2357112 Nov 14 '15 at 20:28

2 Answers2

1

You are looking for reduce function:

from functools import reduce
r = reduce(lambda x,y: x*y, [1,2,3,4,5])
# r = 120
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
HeyYO
  • 1,989
  • 17
  • 24
  • 4
    you can replace `lambda` by python's inbuilt `mul` ... `from operator import mul` and then pass `mul` to `reduce` func instead of `lambda`... – labheshr Nov 14 '15 at 21:02
-2

To itterate through a list you can use:

list=[1,2,3,4]
for x in list:
    print(x)

Example with your output:

list=[1,2,3,4]
stringY=''
for x in list:
    print(x)
    if stringY is not '':
        stringY = stringY + '*' + str(x)
    else:
        stringY = stringY + str(x)

print(stringY)

Also have a look here: Link
This might also show what you are looking for.

Tenzin
  • 2,415
  • 2
  • 23
  • 36