Bird
Raised Fist0
Pythonprogramming~10 mins

Variable-length keyword arguments (**kwargs) in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Variable-length keyword arguments (**kwargs)
Function called with named arguments
Collect all extra named args into kwargs dict
Inside function: kwargs is a dict
Use kwargs keys and values as needed
Function completes and returns
When a function is called with extra named arguments, Python collects them into a dictionary called kwargs inside the function.
Execution Sample
Python
def greet(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

greet(name='Alice', age=30)
This code collects extra named arguments into kwargs and prints each key and value.
Execution Table
StepActionkwargs contentOutput
1Function greet called with name='Alice', age=30{} (before collection)
2Collect extra named arguments into kwargs{'name': 'Alice', 'age': 30}
3Start loop over kwargs.items(){'name': 'Alice', 'age': 30}
4First iteration: key='name', value='Alice'{'name': 'Alice', 'age': 30}name: Alice
5Second iteration: key='age', value=30{'name': 'Alice', 'age': 30}age: 30
6Loop ends, function ends{'name': 'Alice', 'age': 30}
💡 All items in kwargs processed, function returns None
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 5Final
kwargs{}{'name': 'Alice', 'age': 30}{'name': 'Alice', 'age': 30}{'name': 'Alice', 'age': 30}{'name': 'Alice', 'age': 30}
keyN/AN/A'name''age'N/A
valueN/AN/A'Alice'30N/A
Key Moments - 3 Insights
Why is kwargs a dictionary and not a list or other type?
Because **kwargs collects named arguments as key-value pairs, so Python stores them in a dictionary as shown in execution_table step 2.
What happens if no extra named arguments are passed?
kwargs will be an empty dictionary {} and the loop inside the function will not run, so no output is produced (see variable_tracker start state).
Can kwargs keys be accessed like normal dictionary keys?
Yes, inside the function kwargs behaves like a normal dictionary, so you can use methods like items() or access keys directly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the value of key and value?
Akey='Alice', value='name'
Bkey='age', value=30
Ckey='name', value='Alice'
Dkey='age', value='Alice'
💡 Hint
Check execution_table row with Step 4 under 'Action' and 'Output' columns.
At which step does kwargs get filled with the passed named arguments?
AStep 2
BStep 1
CStep 3
DStep 6
💡 Hint
Look at execution_table row Step 2 where kwargs content changes from empty to filled.
If greet() is called with no arguments, what will kwargs be inside the function?
AA dictionary with keys 'name' and 'age'
BAn empty dictionary {}
CNone
DA list of arguments
💡 Hint
Refer to key_moments answer about no extra named arguments and variable_tracker start state.
Concept Snapshot
def func(**kwargs):
  # kwargs is a dict of extra named args
  for key, value in kwargs.items():
    print(f"{key}: {value}")

Use **kwargs to accept any number of named arguments.
Inside the function, kwargs behaves like a dictionary.
Full Transcript
This example shows how Python collects extra named arguments passed to a function into a dictionary called kwargs. When greet(name='Alice', age=30) is called, kwargs becomes {'name': 'Alice', 'age': 30}. The function loops over this dictionary and prints each key and value. If no extra named arguments are passed, kwargs is empty. This helps functions accept flexible named inputs.

Practice

(1/5)
1. What does **kwargs allow you to do in a Python function?
easy
A. Pass a variable number of keyword arguments as a dictionary
B. Pass a variable number of positional arguments as a tuple
C. Return multiple values from a function
D. Define a function without any parameters

Solution

  1. Step 1: Understand **kwargs usage

    **kwargs collects extra keyword arguments into a dictionary inside the function.
  2. Step 2: Compare with other options

    Pass a variable number of positional arguments as a tuple describes *args, not **kwargs. Options A and C are unrelated to **kwargs.
  3. Final Answer:

    Pass a variable number of keyword arguments as a dictionary -> Option A
  4. Quick Check:

    **kwargs = keyword args dict [OK]
Hint: Remember: **kwargs collects named arguments as a dict [OK]
Common Mistakes:
  • Confusing *args with **kwargs
  • Thinking **kwargs collects positional arguments
  • Believing **kwargs returns multiple values
2. Which of the following is the correct way to define a function that accepts variable keyword arguments?
easy
A. def func(*kwargs):
B. def func(**kwargs):
C. def func(**kwargs, *args):
D. def func(kwargs**):

Solution

  1. Step 1: Recall correct syntax for keyword arguments

    The correct syntax to accept variable keyword arguments is **kwargs.
  2. Step 2: Check each option

    def func(*kwargs): uses single star which is for positional args. def func(**kwargs, *args): is invalid syntax because **kwargs must come after any *args. def func(kwargs**): is invalid syntax.
  3. Final Answer:

    def func(**kwargs): -> Option B
  4. Quick Check:

    Double star before kwargs means keyword args [OK]
Hint: Use double star ** before kwargs in function definition [OK]
Common Mistakes:
  • Using single star * instead of double star **
  • Placing **kwargs incorrectly in parameters
  • Writing invalid syntax like kwargs**
3. What will be the output of the following code?
def greet(**kwargs):
    if 'name' in kwargs:
        return f"Hello, {kwargs['name']}!"
    else:
        return "Hello, stranger!"

print(greet(name='Alice'))
print(greet(age=30))
medium
A. Error: KeyError
B. Hello, Alice!\nHello, None!
C. Hello, stranger!\nHello, stranger!
D. Hello, Alice!\nHello, stranger!

Solution

  1. Step 1: Analyze function behavior with kwargs

    The function checks if 'name' is a key in kwargs. If yes, it returns a greeting with that name; otherwise, it returns "Hello, stranger!".
  2. Step 2: Evaluate each print statement

    First call passes name='Alice', so output is "Hello, Alice!". Second call passes age=30, no 'name' key, so output is "Hello, stranger!".
  3. Final Answer:

    Hello, Alice!\nHello, stranger! -> Option D
  4. Quick Check:

    Check key in kwargs dict to decide greeting [OK]
Hint: Check if 'name' key exists in kwargs before using it [OK]
Common Mistakes:
  • Assuming missing key returns None instead of else case
  • Expecting KeyError without checking key presence
  • Confusing positional and keyword arguments
4. Identify the error in the following code and choose the correct fix:
def show_info(**kwargs):
    print(kwargs['age'])

show_info(name='Bob')
medium
A. Change **kwargs to *args
B. Remove the print statement
C. Add a default value for 'age' using kwargs.get('age', default)
D. Call show_info with age parameter

Solution

  1. Step 1: Identify the error cause

    The function tries to print kwargs['age'], but the call only passes name='Bob'. This causes a KeyError because 'age' key is missing.
  2. Step 2: Choose the fix

    Using kwargs.get('age', default) safely returns a default value if 'age' is missing, avoiding the error.
  3. Final Answer:

    Add a default value for 'age' using kwargs.get('age', default) -> Option C
  4. Quick Check:

    Use kwargs.get() to avoid KeyError on missing keys [OK]
Hint: Use kwargs.get('key', default) to avoid missing key errors [OK]
Common Mistakes:
  • Not handling missing keys causing KeyError
  • Confusing *args and **kwargs
  • Ignoring the need to pass required keys
5. You want to write a function build_profile that accepts a mandatory username and any number of additional keyword arguments describing user info. Which of the following implementations correctly returns a dictionary with all this data?
hard
A. def build_profile(username, **kwargs): profile = {'username': username} profile.update(kwargs) return profile
B. def build_profile(**kwargs, username): kwargs['username'] = username return kwargs
C. def build_profile(username, **kwargs): profile = kwargs profile['username'] = username return profile
D. def build_profile(username, *args): profile = dict(args) profile['username'] = username return profile

Solution

  1. Step 1: Understand function parameter order

    Mandatory parameters must come before **kwargs. def build_profile(**kwargs, username): kwargs['username'] = username return kwargs is invalid syntax because **kwargs must be last.
  2. Step 2: Check dictionary construction

    def build_profile(username, **kwargs): profile = kwargs profile['username'] = username return profile modifies kwargs directly, which can cause unexpected side effects. def build_profile(username, **kwargs): profile = {'username': username} profile.update(kwargs) return profile creates a new dict with username, then updates with kwargs safely.
  3. Step 3: Evaluate *args usage

    def build_profile(username, *args): profile = dict(args) profile['username'] = username return profile uses *args which collects positional arguments, not keyword arguments, so it won't work as intended.
  4. Final Answer:

    def build_profile(username, **kwargs): profile = {'username': username} profile.update(kwargs) return profile -> Option A
  5. Quick Check:

    Use username param first, then update dict with kwargs [OK]
Hint: Put mandatory params before **kwargs and update dict safely [OK]
Common Mistakes:
  • Placing **kwargs before mandatory parameters
  • Modifying kwargs dict directly
  • Using *args instead of **kwargs for keyword data