In the previous chapter, you created functions and passed values into them. Python gives you many flexible ways to pass those values: by position, by name, with default values, or even an unknown number of values.
Understanding these options helps you write functions that are easy to call and hard to misuse. It is also a very common topic in interviews.
Parameters vs Arguments
These two words are often mixed up, so let's get them clear first:
A parameter is the variable name listed in the function definition. An argument is the actual value you pass when calling the function.
def greet(name): # name is a PARAMETER
print(f"Hello, {name}!")
greet("Riya") # "Riya" is an ARGUMENTAn easy way to remember: the parameter is the empty box, the argument is what you put inside it.
1. Positional Arguments
With positional arguments, values are matched to parameters in order: first argument to first parameter, second to second, and so on.
def introduce(name, age):
print(f"{name} is {age} years old.")
introduce("Arjun", 21)
introduce(21, "Arjun")Output:
Arjun is 21 years old.
21 is Arjun years old.The second call runs without any error, but the result is wrong. With positional arguments, order matters.
Passing the Wrong Number of Arguments
If you pass too few or too many positional arguments, Python raises a TypeError:
def greet(name):
print(f"Hello, {name}!")
greet()Output:
TypeError: greet() missing 1 required positional argument: 'name'def greet(name):
print(f"Hello, {name}!")
greet("Riya", "Arjun")Output:
TypeError: greet() takes 1 positional argument but 2 were given2. Keyword Arguments
With keyword arguments, you pass values using the parameter name. Now the order no longer matters:
def introduce(name, age):
print(f"{name} is {age} years old.")
introduce(name="Arjun", age=21)
introduce(age=21, name="Arjun")Output:
Arjun is 21 years old.
Arjun is 21 years old.Keyword arguments also make calls easier to read. Compare book_ticket("Delhi", "Mumbai", 2) with book_ticket(source="Delhi", destination="Mumbai", passengers=2).
Mixing Positional and Keyword Arguments
You can mix both styles, but positional arguments must come first:
def introduce(name, age, city):
print(f"{name}, {age}, from {city}")
introduce("Meera", city="Pune", age=20)Output:
Meera, 20, from PunePutting a positional argument after a keyword argument is an error:
introduce(name="Meera", 20, "Pune")
# SyntaxError: positional argument follows keyword argument3. Default Arguments
You can give a parameter a default value. If the caller doesn't pass that argument, the default is used:
def greet(name, message="Good morning"):
print(f"{message}, {name}!")
greet("Riya")
greet("Arjun", "Good night")
greet("Kabir", message="Welcome")Output:
Good morning, Riya!
Good night, Arjun!
Welcome, Kabir!You've already used defaults without knowing it. print() has sep=" " and end="\n" as default arguments, which is why you can change them only when you need to.
Rule: Defaults Come Last
Parameters with default values must come after parameters without defaults:
def greet(message="Hello", name): # wrong
pass
# SyntaxError: parameter without a default follows parameter with a defaultThe correct order is def greet(name, message="Hello"):.
Pitfall: Mutable Default Values
This is a classic interview question. Look at this function, which uses a list as a default value (append() adds an item to the end of a list; you'll learn more in the Lists chapters):
def add_item(item, cart=[]):
cart.append(item)
return cart
print(add_item("pen"))
print(add_item("book"))Output:
['pen']
['pen', 'book']You might expect the second call to return ['book']. But a default value is created only once, when the function is defined, not every time it is called. So every call shares the same list.
The standard fix is to use None as the default and create a new list inside the function:
def add_item(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
print(add_item("pen"))
print(add_item("book"))Output:
['pen']
['book']Never use a mutable object (like a list or dictionary) as a default value. Use None instead.
4. Variable-Length Arguments: *args
Sometimes you don't know how many values will be passed. For example, a function that adds up any number of numbers. Put a * before a parameter name to collect all extra positional arguments:
def total(*numbers):
print(numbers)
result = 0
for n in numbers:
result += n
return result
print(total(1, 2))
print(total(10, 20, 30, 40))
print(total())Output:
(1, 2)
3
(10, 20, 30, 40)
100
()
0All the values are packed into a tuple (an ordered collection that cannot be changed, covered in the Tuples chapter). You can loop over it just like a list.
The name args is just a convention. The * is what matters, so *numbers works exactly like *args.
5. Variable-Length Keyword Arguments: **kwargs
Two stars ** collect all extra keyword arguments into a dictionary (name-value pairs, covered in the Dictionaries chapter):
def student_profile(name, **details):
print("Name:", name)
for key, value in details.items():
print(f"{key}: {value}")
student_profile("Ananya", branch="CSE", year=3, city="Chennai")Output:
Name: Ananya
branch: CSE
year: 3
city: ChennaiHere, details becomes {'branch': 'CSE', 'year': 3, 'city': 'Chennai'}. Again, the name kwargs is only a convention.
6. Keyword-Only and Positional-Only Parameters
Python also lets you force how certain arguments must be passed.
Keyword-Only (after *)
Any parameter after a bare * (or after *args) must be passed by keyword:
def transfer(amount, *, to_account):
print(f"Sending {amount} to {to_account}")
transfer(500, to_account="ACC123")Output:
Sending 500 to ACC123Calling transfer(500, "ACC123") gives TypeError: transfer() takes 1 positional argument but 2 were given. This makes important arguments clear at the call site.
Positional-Only (before /)
Since Python 3.8, parameters before a / must be passed by position:
def power(base, exponent, /):
return base ** exponent
print(power(2, 5))Output:
32Calling power(base=2, exponent=5) raises a TypeError. Many built-in functions, like len(), work this way.
The Full Order
When you combine everything, parameters must appear in this order:
def f(pos_only, /, normal, *args, kw_only, **kwargs):
| | | | |
| | | | +-- extra keyword args (dict)
| | | +------------ must be passed by keyword
| | +-------------------- extra positional args (tuple)
| +---------------------------- positional or keyword
+------------------------------------------ positional onlyYou will rarely need all of them at once, but knowing the order helps you read library code.
Unpacking Arguments with * and **
The stars also work the other way round, at the call site. They unpack a collection into separate arguments:
def introduce(name, age, city):
print(f"{name}, {age}, from {city}")
info = ["Rahul", 22, "Jaipur"]
introduce(*info) # same as introduce("Rahul", 22, "Jaipur")
data = {"name": "Sneha", "age": 19, "city": "Kochi"}
introduce(**data) # same as introduce(name="Sneha", age=19, city="Kochi")Output:
Rahul, 22, from Jaipur
Sneha, 19, from KochiHow Are Arguments Passed? (Interview Favourite)
Python passes arguments by object reference (sometimes called "pass by assignment"). The parameter becomes a new name for the same object the caller passed.
If the object is immutable (int, float, str, tuple), the function cannot change it. Assigning a new value only changes the local name.
If the object is mutable (like a list), changes made inside the object are visible to the caller.
def change(number, items):
number = 100 # rebinds the local name only
items.append(4) # modifies the shared list
x = 5
my_list = [1, 2, 3]
change(x, my_list)
print(x)
print(my_list)Output:
5
[1, 2, 3, 4]x is unchanged, but my_list was modified, because the function and the caller were looking at the same list.
Summary
Type | Example | Key point |
|---|---|---|
Positional |
| Matched by order |
Keyword |
| Matched by name, order doesn't matter |
Default |
| Used if no value is passed; must come last |
|
| Extra positional values as a tuple |
|
| Extra keyword values as a dictionary |
Keyword-only |
|
|
Positional-only |
|
|
Remember the two classic interview points: don't use mutable default values, and Python passes arguments by object reference.