in-built functions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nonemsludo
    New Member
    • Apr 2010
    • 15

    in-built functions

    Is there any particular function to find the product of a list like you would have for sum[list of integers] to find sum
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Err...yes. It's called the 'product' function, and you call it by typing 'product'. I know python's syntax can be hard to guess!

    Comment

    • Nonemsludo
      New Member
      • Apr 2010
      • 15

      #3
      >>> import math
      >>> d=[elem for elem in range(1,10)]
      >>> d
      [1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> product(d)
      Traceback (most recent call last):
      that's what I get
      File "<stdin>", line 1, in <module>
      NameError: name 'product' is not defined

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Following are two ways using built-in function reduce().
        Code:
        >>> reduce(lambda x, y: x*y, [2,3,4,5], 1)
        120
        >>> import operator
        >>> reduce(operator.mul, [2,3,4,5])
        120

        Comment

        Working...