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

*args, packing and slices?

In Python Collections, Tuples section, there's a "Packing" challenge as follows:

Let's play with the *args pattern.

Create a function named multiply that takes any number of arguments. Return the product (multiplied value) of all of the supplied arguments. The type of argument shouldn't matter.

Slices might come in handy for this one.

I solved it by using a for loop and then multiplying each value inside the tuple, no biggie, BUT I cannot figure out how I would fit slices into a solution.

Did anybody out there use slices? How would one go about it? Cheers!

1 Answer

Steven Parker
Steven Parker
243,318 Points

You probably solved it like I did.

I started with a product of 1, and then multiplied by each argument.

But you could do it by starting with the first argument and multiplying by each of the others. You could use a slice to get the "others".

I started with the first argument and went from there. I didn't want to post my code so others won't be spoiled by it. And that's not the point really. I just want to know how would slices fit into this.

You can't mutiply tuple item by tuple item like: nums[0:1] * nums[1:2], and if you multiply an int by a tuple the result is not what we are expecting in this exercise.

Would the slice be used for looping the items inside de tuple?

Steven Parker
Steven Parker
243,318 Points

Right, so I'm guessing you created a loop using a range, and then indexed into the list? But using the slice you could do something like this:

for val in nums[1:]: