Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!

from functools import reduce
from operator import mul

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

2 Answers

Chris Freeman
Chris Freeman
Treehouse Moderator 68,064 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