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 Functional Python The Lambda Lambada Partial

Matthew Smith
Matthew Smith
3,083 Points

Why would I use partial, and not list comprehension?

In the challenge, I was asked to use partial and map to produce the discounted lists. While I understood how to use partial to solve the problem, I don't understand why I would use it.

Is this just a bad example of where partial produces better code, or is it more of a preference?

I would be keen to see an example where partial is a better alternative to list comprehension.

discounts.py
from functools import partial

prices = [
    10.50,
    9.99,
    0.25,
    1.50,
    8.79,
    101.25,
    8.00
]


def discount(price, amount):
    return price - price * (amount/100)

discount_10 = partial(discount, amount = 10)
discount_25 = partial(discount, amount = 25)
discount_50 = partial(discount, amount = 50)

prices_10 = map(discount_10, prices)
prices_25 = map(discount_25, prices)
prices_50 = map(discount_50, prices)

list_prices_10 = [ discount(price, 10) for price in prices]
Matthew Smith
Matthew Smith
3,083 Points

as a sidenote for the moderators, is there a better way of me posing a question, and labelling it as a "spoiler" for folks looking for hints, but not the solution?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Unfortunately there isn’t. It’s been a long outstanding request to allow a revealing tag that would meet this need. Years ago embedded JavaScript was allow to hide code within posts, but was disallowed quickly.

You could put the spoiler code in a comment so that it’s less obvious as a poor substitute.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The primary lesson is to understand how partials work, so a simple example was chosen.

In a practical example, the base function may have a dozen parameters, of which, the local usage only needs to vary one of them. To repeatedly type the remaining β€œconstant” parameters would be tedious and make the code harder to read. The reader would have to verify to be sure only the desired one was changing.

Sometime readability is sufficient enough reason. Otherwise the above code could have been written as:

lp_10, lp_25, lp_50 = [
    [price - price * (amount/100)
        for price in prices]
    for amount in (10, 25, 50)]

Post back if you need more help. Good luck!!!