How to Merge Two Lists in Python

Merge two Python lists into a single combined list by appending each element with a simple loop, achieving the same result as the + operator.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

14 lines
Python 3.9+
def merge_lists(list_a, list_b):
    merged = []
    for item in list_a:
        merged.append(item)
    for item in list_b:
        merged.append(item)
    return merged


if __name__ == "__main__":
    fruits = ["apple", "banana"]
    vegetables = ["carrot", "spinach"]
    result = merge_lists(fruits, vegetables)
    print(result)

Output

stdout
['apple', 'banana', 'carrot', 'spinach']

How it works

This helper function creates a new empty list and then iterates through each input list separately, appending every item to the merged result. The for loops guarantee order is preserved, with all elements from list_a coming before list_b. While the built-in + operator or extend() method is more concise, writing the loop explicitly shows exactly how list concatenation works under the hood and makes the logic readable for beginners.

Common mistakes

  • Forgetting that the function creates a new list rather than modifying the originals
  • Using `append` with the entire list instead of iterating to add individual elements
  • Assuming the input lists remain unchanged after merging (they do, since we return a new list)

Variations

  1. Use the `+` operator: `result = fruits + vegetables`
  2. Use `list_a.extend(list_b)` to modify the first list in place, or a list comprehension with nested loops

Real-world use cases

  • Combining two API response pages into one list before displaying results to the user.
  • Merging user-provided tags from multiple configuration sources into a single list for validation.
  • Joining separate error logs from different services into one list for aggregated reporting.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.