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 trialJacques Plomion
2,446 PointsCall a function with a random number of arguments
I have a function like that:
def my_function(*args):
for arg in args:
print(arg)
and I would like to call it with a random number of arguments. Something like:
args = tuple(random.randint(1, 500) for _ in range(10))
my_function(args)
And I can't make it work. Any suggestions?
Thanks
Jacques
2 Answers
Chris Freeman
Treehouse Moderator 68,460 PointsJacques Plomion, you are correct that my_function
is seeing the tuple as a single argument. The power of the asterisk in *args
can be used in two ways:
- as a catchall to receive an arbitrary number of arguments, and
- to expand a container into individual arguments
The second way is used when you see code like:
def __init__(*args, **kwargs): # used here to catch all arguments
super().__init(*args, **kwargs) # used here to expand back to individual arguments
So, the simple solution is to call your function as: my_function(*args)
>>> import random
>>> args = tuple(random.randint(1, 500) for _ in range(10))
>>> args
(284, 481, 276, 323, 22, 1, 274, 395, 425, 381)
>>> my_function(args)
(284, 481, 276, 323, 22, 1, 274, 395, 425, 381)
>>> my_function(*args)
284
481
276
323
22
1
274
395
425
381
Post back if you have more questions. Good Luck!!
Clayton Perszyk
Treehouse Moderator 48,850 PointsHey Jacques,
You need to import the random library:
import random
then you can call:
random.randint(n1, n2)
or
from random import randint
then you can call:
randint(n1, n2)
Jacques Plomion
2,446 PointsHi Clayton,
Thanks for taking the time to respond to me. I guess I didn't explain what I am trying to do well enough so let me try again:
I am trying to call my_function
with a random number of arguments in *args. The args would be determined randomly when I run the script.
So doing:
args = tuple(random.randint(1, 500) for _ in range(10))
my_function(args)
creates a tuple with a random number of arguments and when I call my_function
I get this result:
(332, 224, 406, 410, 352, 306, 245, 455, 456, 89) # for example
I think this is because my tuple is seen as one argument (a tuple) when I would like it to be seen as several integer arguments. I hope it is more clear. And again, thank you for helping with this.
Jacques
Jacques Plomion
2,446 PointsJacques Plomion
2,446 PointsThanks Chris.