How to write functions in Python that accept any number of arguments

PythonServer Side ProgrammingProgramming

Problem

You want to write a function that accepts any number of input arguments.

Solution

The * argument in python can accepts any number of arguments. We will understand this with an example of finding out the average of any given two or more numbers. In the below example, rest_arg is a tuple of all the extra arguments (in our case numbers) passed. The function treats the arguments as a sequence in performing average calculation.

# Sample function to find the average of the given numbers
def define_average(first_arg, *rest_arg):
average = (first_arg + sum(rest_arg)) / (1 + len(rest_arg))
print(f"Output \n *** The average for the given numbers {average}")

# Call the function with two numbers
define_average(1, 2)

Output

*** The average for the given numbers 1.5


# Call the function with more numbers
define_average(1, 2, 3, 4)

Output

*** The average for the given numbers 2.5

To accept any number of keyword arguments, use an argument that starts with **.

def player_stats(player_name, player_country, **player_titles):
print(f"Output \n*** Type of player_titles - {type(player_titles)}")
titles = ' AND '.join('{} : {}'.format(key, value) for key, value in player_titles.items())

print(f"*** Type of titles post conversion - {type(titles)}")
stats = 'The player - {name} from {country} has {titles}'.format(name = player_name,
country=player_country,
titles=titles)
return stats

player_stats('Roger Federer','Switzerland', Grandslams = 20, ATP = 103)

Output

*** Type of player_titles - <class 'dict'>
*** Type of titles post conversion - <class 'str'>


'The player - Roger Federer from Switzerland has Grandslams : 20 AND ATP : 103'

Here in above example, player_titles is a dictionary that holds the passed keyword arguments.

If you want a function that can accept both any number of positional and keyword-only arguments, use * and ** together

def func_anyargs(*args, **kwargs):
print(args) # A tuple
print(kwargs) # A dict

With this function, all of the positional arguments are placed into a tuple args, and all of the keyword arguments are placed into a dictionary kwargs.

raja
Published on 09-Nov-2020 10:31:24
Advertisements