How to Merge Lists in Python with Default Parameters
This Python function merges two lists using the + operator and demonstrates default parameters, allowing the second argument to be omitted.
Python code
14 linesdef merge_lists(list1, list2=["default"]):
"""Merge two lists and return the combined result."""
return list1 + list2
if __name__ == "__main__":
# Example with default parameter
print("With default:", merge_lists([1, 2, 3]))
# Example with both arguments provided
print("With custom:", merge_lists([1, 2, 3], [4, 5, 6]))
# Example with strings
print("Strings:", merge_lists(["apple", "banana"], ["cherry"]))
Output
With default: [1, 2, 3, 'default']
With custom: [1, 2, 3, 4, 5, 6]
Strings: ['apple', 'banana', 'cherry']
How it works
The merge_lists function takes two list parameters, with list2 having a default value of ["default"]. When called with only one list, Python automatically uses the default for list2, appending it to the first list. The + operator is overloaded for lists to concatenate them, producing a new list without modifying the originals. Default parameters are evaluated once at function definition time, so avoid mutable defaults if you need a fresh empty list each call. The if __name__ == "__main__": block ensures the test code runs only when the script is executed directly, not when imported.
Common mistakes
- Using a mutable default like [] and expecting a new empty list each call — it's shared across calls.
- Forgetting that + creates a new list, so original lists remain unchanged.
- Passing incompatible types (e.g., string instead of list) causes TypeError.
Variations
- Use `list2.extend(list1)` to modify in place, but that returns None.
- Use `itertools.chain` for lazy concatenation of large lists.
Real-world use cases
- Creating a flexible utility function that can merge user-provided lists with a sensible fallback, such as adding preset feature flags.
- Combining configuration lists from multiple sources, where one source is optional and defaults to an empty or placeholder set.
- Building a test helper that merges base items with optional extra items for parameterized test data.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.