Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Tuples Packing

Is there a generator expression solution to multiply() ?

Hi all. I'm working hard to become an intermediate Python programmer. I've received tons of love and support along the way. Thank you all :)

Question: would there be a generator expression approach to this code challenge? I've tried but I don't know where to get started.

Here's some background:

Regarding using reduce, one of the reasons it have been moved from a builtin function to being part of functools, is because it wasn't found to be superior to using a for loop. According to the Python 3 release notes:

"Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable."

Thank you all!

twoples.py
from functools import reduce
from operator import mul

def multiply(*args):
    return reduce(mul, args)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

In short, there is not one I know of. There has been discussion to add a sum() analog called mult() but it hasn't gotten traction.

If a short brew-your-own solution isn't viable via a loop (or yes functools.reduce()), you can use numpy.prod if needed.

Once again, numpy saves the day! :) much appreciated, as always, Chris