Home > python > Product of the elements in a list

Product of the elements in a list

Design goal: should be just one line, without using explicit iteration over the list.

Sum of the elements:

>>> li = [2,3,5]
>>> sum(li)
10

Product of the elements:

>>> li = [2,3,5]
>>> from operator import mul
>>> reduce(mul, li)
30
About these ads
Categories: python Tags: , ,
  1. variedthoughts
    May 2, 2012 at 18:03 | #1

    Nice simple explanation.
    I sometimes see explanations of for loops with examples of how to use them for summation.
    And I think “No! Just use sum()!”

  1. No trackbacks yet.
You must be logged in to post a comment.
Follow

Get every new post delivered to your Inbox.

Join 63 other followers

%d bloggers like this: