What Are Arguments in Python
Arguments in Python are values passed to a function when it's called, allowing the function to receive input and produce output based on that input. They appear inside parentheses after the function name and are assigned to parameters defined in the function's signature.
When you define a function using def, you specify parameters-names that act as placeholders for incoming data. When you call the function, you supply actual values, known as arguments, which fill those placeholders. For example, defining def greet(name): sets up a parameter named name. Calling greet("Alice") passes "Alice" as an argument.
Python supports several argument types: positional, keyword, default, and variable-length. Each affects how data flows into a function and influences behavior. Understanding them prevents bugs and improves code clarity.
How Arguments Work in Function Calls
When a function is invoked, Python evaluates the arguments and assigns them to the corresponding parameters in the order they appear. This process is called argument passing. The function then executes using those values.
For instance, consider this function:
def multiply(a, b):
return a * b
result = multiply(3, 4)
print(result) # Outputs: 12
Here, 3 and 4 are arguments passed to the parameters a and b. The function multiplies them and returns 12.
Python uses pass-by-object-reference for arguments. This means that mutable objects (like lists or dictionaries) can be modified inside the function, and changes may persist outside. Immutable objects (like integers or strings) cannot be changed in place. This behavior often surprises beginners who expect arguments to behave like values in other languages.
Types of Arguments in Python
Python offers four main argument types: positional, keyword, default, and variable-length. Each serves a different purpose and alters how functions are called.
| Type | Usage Example | Key Feature |
|---|---|---|
| Positional | func(1, 2) |
Order matters; arguments match parameters by position. |
| Keyword | func(b=2, a=1) |
Order doesn't matter; uses parameter names to assign values. |
| Default | def func(x=10): |
Parameter has a fallback value if not supplied. |
| Variable-length | def func(*args, **kwargs) |
Accepts any number of unnamed or named arguments. |
Positional arguments are the most common. They rely on correct order. If you swap the order, the result changes. For example, calling max(5, 10) returns 10, but max(10, 5) returns 10-the same result-but calling min(10, 5) returns 5, not 10.
Keyword arguments improve readability and reduce errors. Instead of guessing which value goes where, you name the parameter explicitly. This is especially useful in functions with many parameters. For example:
def create_user(name, email, age=18, active=True):
return {"name": name, "email": email, "age": age, "active": active}
user = create_user(email="[email protected]", name="Alice")
Using keyword arguments makes it clear what each value represents, even if you skip optional ones.
Common Misconceptions and Pitfalls
A frequent misunderstanding is that Python passes arguments by value. It does not. It uses pass-by-object-reference. This means that while primitive values like integers are copied, complex objects like lists are passed by reference. Modifying a list inside a function changes the original list.
Consider this example:
def append_to_list(item, lst=[]):
lst.append(item)
return lst
print(append_to_list("a")) # ['a']
print(append_to_list("b")) # ['a', 'b'] - unexpected!
The problem lies in using a mutable default argument. The empty list is created once when the function is defined, not each time it's called. So all calls share the same list. This is a well-documented gotcha in the Python documentation.
To fix it, use None as the default and initialize inside the function:
def append_to_list(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
This avoids shared state and prevents silent bugs.
Practical Examples and Real-World Usage
Functions often combine argument types. A real-world example is a logging function that accepts both required and optional inputs:
def log_event(message, level="info", timestamp=None, metadata=None):
if timestamp is None:
import datetime
timestamp = datetime.datetime.now().isoformat()
if metadata is None:
metadata = {}
print(f"[{level}] {timestamp} - {message}")
if metadata:
print(f" Metadata: {metadata}")
log_event("User logged in", level="warning", metadata={"user_id": 123})
This function uses positional (message), keyword (level, timestamp), default (timestamp, metadata), and variable-length (via metadata dict) arguments.
I once built a configuration loader that accepted a file path and optional environment variables. Using keyword arguments made it easy to set defaults and override only what was needed. The function remained readable even with ten options.
Another advanced pattern uses *args and **kwargs to accept variable numbers of arguments. This is essential for decorators and wrappers. For example:
def wrapper(func, *args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
return func(*args, **kwargs)
def add(a, b):
return a + b
wrapper(add, 3, 5) # Calls add(3, 5), prints info first.
This flexibility allows functions to adapt to unknown input counts, making code reusable across different contexts.
What Are Arguments in Python - Final Summary
Arguments in Python are the values passed into a function during a call. They enable changing behavior by supplying data to functions. Understanding positional, keyword, default, and variable-length arguments ensures correct function usage and prevents subtle bugs.
Always avoid mutable objects as default arguments. Use None instead. This rule, emphasized in the official Python tutorial and confirmed by the Python data model documentation, prevents shared state issues.
Mastering what are arguments in Python improves code reliability and maintainability. building a library, proper argument handling is foundational.
For further reading on handling external inputs, see this guide.