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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 30 other followers

%d bloggers like this: