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

touples packing challenge clue

In touples packing challenge " write a function 'multiply' which should take any number of arguments and return their product, type of the data shouldn't matter", the instructor mentioned, "slices might become handy for this". I am not able to relate how slices can be handy in solving this. Could someone please help me with this?

4 Answers

I have been writing python for 15 years, and I have no idea. Maybe you could do something like:

multiply.py
def multiply(*args):
    acc = 1
    for ii in range(len(args)):
        acc = acc * args[ii]
    return acc

but that feels forced when you could do

multiply.py
def multiply(*args):
    acc = 1
    for ii in args:
        acc = acc * ii
    return acc

Could someone explain to me how Myers Carpenters second code works? I can't work it out

Matthew Byrne : Look at the insides of the function with print(). Try adding lines like print("args: {!r}".format(args)) and then run it to see what happens:

multiply.py
def multiply(*args):
    print("args: {!r}".format(args))
    acc = 1
    for ii in args:
        print("ii: {!r}".format(ii))
        acc = acc * ii
    return acc

print(multiply(1, 2, 3))
myers@toad:~$ python multiply.py
args: (1, 2, 3)
ii: 1
ii: 2
ii: 3
6
Alan Kuo
Alan Kuo
7,697 Points

I was struck on this as well I wrote something similar to your code but it makes no sense I copied your code and ran it on Pycharm it doesn't give me an answer. Since you're a staff can you please advise this to the administrator that I just started to learn Python for 1 week and they gave me this challenge which I feel so stressed out if I can't solve the problem and find no clues for it.

Thanks!

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Slice wise, the hint is pointing at a combination between pulling the first value out and a for loop over a slice of all values except that first one..something like

total = values[0]
for value in values[1:]:
    total *= value

Let me know if that hint doesn't get you there.