Python 3D Academyবাংলা

Any number of arguments: *args

🌍 In real life. A shopkeeper adds up whatever you put on the counter: one item, five items, or none. They don't need to know in advance how many; they just total the pile. And when you order "rice, plus egg and dal", the first item is the main dish and everything after it is extras.

A starred parameter lets a function take a pile of any size like that.

The idea in one sentence: a parameter like *nums collects all the extra positional arguments into a tuple, so a function can take any number of them, even none.

Its words:

  • *args: a starred parameter; args is the usual name, but any name works
  • extra positional arguments: values left over after the normal parameters are filled
  • unpacking in a call: f(*my_list) spreads a list into separate arguments

Step by step, for order("rice", "egg", "dal") with def order(food, *extras)::

  1. food takes the first value, "rice".
  2. *extras collects everything left, as a tuple: ("egg", "dal").
  3. With just order("bread"), extras is the empty tuple ().
def total(*nums):
    return sum(nums)

print(total(1, 2, 3))
print(total(10))
print(total())

Normal parameters come first and take their values first; the starred one collects whatever is left:

def order(food, *extras):
    print("Main:", food)
    print("Extras:", extras)

order("rice", "egg", "dal")
order("bread")

The star works the other way round in a call: *my_list spreads a list out into separate arguments.

def total(*nums):
    return sum(nums)

scores = [4, 5, 6]
print(total(*scores))
print(max(*scores))

How Python does it. The normal parameters are filled first, from the left; whatever is left over is packed into one tuple. The star in a call does the reverse: it unpacks a list into separate values before the call starts. print(*words) is a neat example: each word becomes its own argument, so print puts spaces between them.

Mistakes and edge cases.

  • Passing a list without the star. total([1, 2]) gives nums a tuple holding one item, the list: ([1, 2],). Write total(*[1, 2]).
  • A star on something you can't loop over. total(*5) stops with a TypeError: the value after * must be a list, tuple or other sequence.
  • Two starred parameters. def f(*a, *b): gives SyntaxError: * argument may appear only once.
  • Forgetting it's a tuple. You can loop over args and use len(args), but you can't append to it.

Quiz

  1. What does this print?

    def count(*things):
        return len(things)
    
    print(count("a", "b", "c"), count())
  2. What does this print?

    def show(first, *rest):
        print(first, rest)
    
    show(1, 2, 3)
  3. What does this print?

    def add(a, b):
        return a + b
    
    pair = [3, 4]
    print(add(*pair))
  4. What type of value does *args hold inside the function?

    • A tuple
    • A list
    • A dictionary
  5. Which line has a mistake?

    def total(*nums):
        return sum(nums)
    
    print(total([1, 2, 3]))

Coding tasks

  1. Write total(*nums) that returns the sum of all its arguments (0 when there are none).

  2. Write biggest(first, *rest) that returns the largest of all its arguments. It always gets at least one.

  3. Write join_words(*words, sep=" ") that returns all the words joined by sep.