Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: 2.5 Functions - Arbitrary Arguments (*args)

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

What are Arbitrary Arguments (*args)?

*args is the short form for Arbitrary Arguments 

If the number of arguments to be passed into the function is unknown, add a (*) before the argument name.

Lets say you want to create a function that will sum up a list of numbers. The most intuitive way will be to create that list and pass it into a function, as shown below. 

 

However, if we do it this way it means that we will have to create a new list every single time. 

So an alternative will be to use*args where you can pass a varying number of positional arguments instead of creating a list to store these arguments.

Lets edit our sum_function()

 

*args is just a name. We can change arg to anything we want like how we changed it to *numbers above.

The important thing here is the unpacking operator (*)

The operator will take all positional arguments given in the input and pack them all into a single iterable object. Take note, the iterable object will be a tuple not a list.

Tuples and lists are similar in all aspects except that tuples are not mutable. Immutable means its values cannot be edited after assignment.

Activity

Write a function that will take in an unknown number of arguments and multiply all of them together and run the function for these 2 sets of numbers:

  • 1,2,3,4,5
  • 12,13,14