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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

14 lines
Python 3.9+
def 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

stdout
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

  1. Use `list2.extend(list1)` to modify in place, but that returns None.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.