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

Anthony Lopez
Anthony Lopez
963 Points

Multiplying with *args

Hey guys,

Not sure why I'm getting:

Bummer: Couldn't multiply valid values together

I'm using a for loop to put each value into an empty list. Then at the end I'm returning the product of taking the first value in the list and multiplying it with the rest of the values of the list.

At least that was my intention. Am I doing this wrong?

Thanks!

twoples.py
def multiply(*args):
    new_list = []
    for arg in args:
        new_list.append(arg)
    return new_list[0] * new_list [1:]

1 Answer

Oskar Lundberg
Oskar Lundberg
9,534 Points

The problem is at the 'new_list[0] * new_list [1:]', Let's say you put in a bunch of ints into the fuction, for example multiple(2, 2, 2, 2) Then new_list would be equal to [2, 2, 2, 2]. The 'new_list[0] * new_list [1:]' part then returns 2 * [2, 2, 2], which comes out as [2, 2, 2, 2, 2, 2] (The list multiplies by the first arg).

I personally didn't solve this challenge with slices, but here is how I solved the challenge:

def multiply(*args):
    product = 0
    for arg in args:
        if product == 0:
            product = arg
        else:
            product *= arg
    return product

^Hope this helps you :D