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.
Python code
14 linesdef 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
['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
- Use the `+` operator: `result = fruits + vegetables`
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.