Intermediate · Functions · topic 20 of 50 · 20 min
*args and **kwargs
Explanation
Any number of arguments: *args
Sometimes you do not know how many values someone will pass. Put a star before a parameter name, like *prices, and Python collects all the extra positional arguments into one tuple with that name. The usual name is *args, short for arguments, but any name works; the star is what matters.
def total(*prices):
print(prices)
return sum(prices)
print(total(40, 25, 60))
print(total())Any number of keyword arguments: **kwargs
def profile(name, **details):
print(name)
for key, value in details.items():
print(" ", key, "=", value)
profile("Asha", city="Pune", age=21)Unpacking when you call: * and **
The stars also work the other way round. When you call a function, *my_list spreads the items of a list into separate positional arguments, and **my_dict spreads a dict into keyword arguments.
def describe(name, city):
return name + " from " + city
pair = ["Ravi", "Chennai"]
info = {"name": "Meena", "city": "Kochi"}
print(describe(*pair))
print(describe(**info))Keyword-only arguments
A parameter that comes after *args, or after a lone *, can only be passed by name. These are called keyword-only arguments. They are useful for options, so that nobody passes True or False in the wrong position by mistake.
def book_ticket(name, *, seat="any", meal=False):
return name + ": seat " + seat + ", meal " + str(meal)
print(book_ticket("Asha", seat="window", meal=True))
print(book_ticket("Ravi"))def book_ticket(name, *, seat="any"):
return name + " " + seat
book_ticket("Asha", "window")The order of parameters
| Order | Kind | Example |
|---|---|---|
| 1 | normal positional | name |
| 2 | with a default | city="Pune" |
| 3 | any number of positional | *marks |
| 4 | keyword-only | urgent=False |
| 5 | any number of keyword | **extra |
def report(name, city="Pune", *marks, urgent=False, **extra):
print(name, city, marks, urgent, extra)
report("Asha", "Delhi", 80, 90, urgent=True, section="B")Watch the lesson
*args and **kwargs · 1/6
In this lesson you will learn how a function can accept any number of arguments.
Prefer a video by a teacher? Find free videos on “python args kwargs explained for beginners” on YouTube ↗
In real life: A UPI payment summary
A small shop gets many UPI payments in a day, and the number changes every day. A function with *amounts can add up any number of payments. Extra details like the shop name and the date are optional, so they come in through **info and are printed only when given.
def day_summary(*amounts, **info):
for key, value in info.items():
print(key, ":", value)
print("Payments:", len(amounts))
print("Total: Rs", sum(amounts))
day_summary(120, 45, 300, 80, shop="Gupta Stores", day="Monday")Practice (0/3 done)
Write a function total(*prices) that returns the sum of any number of prices. Example: total(10, 20, 30) returns 60 and total() returns 0.
Write a function make_profile(name, **details) that returns a dict with the key "name" set to name, plus every keyword argument that was passed. Example: make_profile("Asha", city="Pune") returns {"name": "Asha", "city": "Pune"}.
Write a function ticket_price(base, *, senior=False, tatkal=False). A senior citizen pays 60% of the base fare. Tatkal adds 200 rupees (after any senior discount). senior and tatkal are keyword-only. Example: ticket_price(1000, senior=True, tatkal=True) returns 800.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.