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 Basics (2015) Shopping List App Shopping List Introduction

Dainis Lacey
Dainis Lacey
551 Points

Functions with infinite arguments

hey, I was wondering how to define a function when you don't know how many arguments are going to be entered?

1 Answer

Hey Dainis. The best way is to use arbitrary arguments: *args and **kwargs. for example:

>>> def inf_args_func(*args, **kwargs):
...     for index, value in enumerate(args):
...         print "{} argument is {}".format(index, value)
...     for item in kwargs.items():
...         print "{} = {}".format(item[0], item[1])
...
>>> inf_args_func(1,2,3)
0 argument is 1
1 argument is 2
2 argument is 3
>>> inf_args_func(hi='hello',bye='byebye')
bye = byebye
hi = hello
>>> inf_args_func(4, 5, 6, hi = "Hello", bye = "ByeBye")
0 argument is 4
1 argument is 5
2 argument is 6
bye = ByeBye
hi = Hello

As you can see our function returns as many arguments as you enter. The difference between *args and **kwargs is that args is a tuple of unnamed arguments but kwargs is a dictionary of named arguments. I hope this works for you!