How To Merge Two Lists in Python?

Ayushi Trivedi Last Updated : 23 Jan, 2024
7 min read

Introduction

Merging two lists in Python is a fundamental operation that often arises in programming tasks. Whether you’re dealing with data manipulation, algorithm implementation, or any other coding scenario, the ability to combine the contents of two lists efficiently is a valuable skill. In Python, this task can be accomplished using various methods, offering flexibility based on the specific needs of your code.

It’s a bit like bringing together two groups of friends to create one big gathering – each friend represents an element in the list, and the merging process is akin to uniting these social circles.

Enroll in our free Python Course today.

Python merge two lists

Input:

# Two sample lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

Output:

[1, 2, 3, 'a', 'b', 'c']

Python Join Two Lists

Using the “+” Operator

To join two lists together, we commonly use the “+” symbol. This symbol helps combine all the items from one list with those from another, making the two lists into one.

# Create two lists
list1 = [11,22,33,44,55]
list2 = [66,77,88,99,110 ]

# Use the "+" symbol to join the lists
result_list = list1 + list2

# Print the combined list
print("Combined list using +:", result_list)

Output:

Combined list using +: [11,22,33,44,55,66,77,88,99,110 ]

Time Complexity:
The time complexity is O(n), where ‘n’ represents the total number of elements in both lists. This is because the “+” operator goes through every element in both lists to join them together.

Space Complexity:
The space complexity is O(n), where ‘n’ represents the total number of elements in both lists. This is because a new list is generated to store the merged elements.

Using the extend() method

The extend() method in Python is used to extend a list by appending elements from another iterable (e.g., a list, tuple, or any other iterable). When you use extend(), it modifies the original list in-place, adding elements from the iterable to the end of the list.

extend() method
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Using extend() to merge list2 into list1
list1.extend(list2)

# Print the merged list
print("Merged List:", list1)

list1 = [1, 2, 3]
list2 = [4, 5, 6]

In this example, extend() is used on list1 to append all elements from list2 to it. After executing this code, list1 will contain the merged elements of both lists.

Output:

Merged List: [1, 2, 3, 4, 5, 6]

Time Complexity:

The time complexity of the extend() method in Python is O(n), where n is the number of elements in the iterable being added.

Space Complexity:

The space complexity of the extend() method is O(1), i.e., constant space. The reason for this is that the extend() method modifies the existing list in-place without creating a new list. Regardless of the size of the iterable being added, it only requires a constant amount of additional space.

Using the “*” Operator

In Python, the * operator has multiple uses, and one of them is for list concatenation or repetition. When used with lists, the * operator performs concatenation by combining the elements of two or more lists into a new list. For example, to join or concatenate two lists, you can use the + operator, but the * operator provides a concise way to achieve the same result.

# Initializing lists
fruits1 = ["apple", "banana", "orange"]
fruits2 = ["grape", "watermelon", "kiwi"]

# using * operator to concatenate lists
combined_fruits = [*fruits1, *fruits2]

# Printing concatenated list
print("Concatenated list using * operator: " + str(combined_fruits))

In this example, fruits1 and fruits2 are two lists containing different fruits. The * operator is used to concatenate the lists, resulting in a new list called combined_fruits.

Output:

Concatenated list using * operator: [‘apple’, ‘banana’, ‘orange’, ‘grape’, ‘watermelon’, ‘kiwi’]

Time Complexity:

The time complexity of list concatenation using the * operator is O(n + m), where n and m are the lengths of the two lists being concatenated (fruits1 and fruits2 in this case). This is because each element in both lists needs to be copied to the new list.

Space Complexity:

The space complexity is O(n + m) as well. The new list (combined_fruits) is created to store the concatenated elements of fruits1 and fruits2. The space required is proportional to the sum of the lengths of the two lists.

Using the Naive Method

The naive method of merging two lists involves iterating through the elements of one list and appending each element to the other list.

# Initializing lists
fruits1 = ["apple", "banana", "orange"]
fruits2 = ["grape", "watermelon", "kiwi"]

# Using naive method to merge lists
for fruit in fruits2:
    fruits1.append(fruit)

# Printing concatenated list
print("Concatenated list using naive method: " + str(fruits1))

In this example, fruits1 and fruits2 are two lists containing different fruits. The naive method is used to iterate through the elements of fruits2 and append each element to the end of fruits1. Finally, the merged list is printed.

Output:

Concatenated list using naive method: [‘apple’, ‘banana’, ‘orange’, ‘grape’, ‘watermelon’, ‘kiwi’]

Time Complexity:

The time complexity of the Naive method for merging two lists is O(m), where m is the length of the second list (fruits2). This is because the loop iterates through each element in fruits2 and performs a constant-time operation (appending) for each element.

Space Complexity:

The space complexity is O(1), i.e., constant space. The operation is performed in-place, modifying the existing fruits1 list without creating a new list. The space required is constant and does not depend on the size of the input.

Using the List Comprehension

In the context of merging two lists using list comprehension, the idea is to create a new list by iterating over each element in both lists and including those elements in the new list.

# Initializing lists
letters1 = ['a', 'b', 'c']
letters2 = ['x', 'y', 'z']

# Using list comprehension to concatenate lists
combined_letters = [char for sublist in [letters1, letters2] for char in sublist]

# Printing concatenated list
print("Concatenated list using list comprehension:", combined_letters)

In this example, letters1 and letters2 are two lists containing letters. The list comprehension iterates over each sublist (containing letters1 and letters2) and then iterates over each character in those sublists. The resulting combined_letters list will contain all the letters from both original lists.

Output:

Concatenated list using list comprehension: [‘a’, ‘b’, ‘c’, ‘x’, ‘y’, ‘z’]

Time Complexity:

The time complexity of this list comprehension for concatenating lists is O(n + m), where n and m are the lengths of the two lists (letters1 and letters2). The list comprehension iterates over all elements in both lists to create the new list.

Space Complexity:

The space complexity is O(n + m) as well. The new list (combined_letters) is created to store the concatenated elements of letters1 and letters2. The space required is proportional to the sum of the lengths of the two input lists.

Using the reduce() method

In Python, the reduce() function is part of the functools module, and it is used for cumulative operations on a sequence of elements. The reduce() function takes a binary function (a function that takes two arguments) and a sequence as input. It applies the function cumulatively to the items of the sequence from left to right, reducing the sequence to a single accumulated value.

Python Reduce()
from functools import reduce

# Initializing lists
numbers1 = [1, 2, 3, 4, 5]
numbers2 = [6, 7, 8, 9, 10]

# Create a nested list
nested_numbers = [numbers1, numbers2]

# Use reduce() and lambda function to concatenate lists
result = reduce(lambda x, y: x + y, nested_numbers, [])

# Print the concatenated list
print("Concatenated list using reduce and lambda:", result)

In this example, the reduce() function, along with a lambda function, is used to concatenate two lists. The lambda function adds the elements of the lists, and reduce() applies it iteratively to a nested list, resulting in a concatenated list. The initial value for accumulation is an empty list []. The final result is printed as the output, showcasing a concise approach to list concatenation using reduce() and a lambda function.

Output:

Concatenated list using reduce and lambda: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Time Complexity:

The time complexity is O(n + m), where n and m are the lengths of the two lists (numbers1 and numbers2). The reduce() function iterates over all elements in the nested list, and the lambda function adds each element to the accumulated result.

Space Complexity:

The space complexity is O(n + m) as well. The reduce() function accumulates the result by concatenating the lists, and the space required is proportional to the sum of the lengths of the two input lists. The empty list [] provided as the initial value does not contribute significantly to the space complexity.

Conclusion

In conclusion, merging two lists in Python offers various methods, each with its own advantages. The + operator provides a straightforward and concise approach, while the extend() method efficiently appends elements from one list to another. List comprehension offers a concise way to merge lists by iterating through their elements. For more complex scenarios, the reduce() function from the functools module proves useful, albeit with potential memory considerations.

Choosing the appropriate method depends on factors such as readability, efficiency, and memory usage. The extend() method and list comprehension are generally recommended for merging large lists due to their memory efficiency. Understanding these methods empowers developers to select the most suitable approach based on specific requirements.

You can also refer our other articles to learn and explore about Python list:

Frequently Asked Question

Q: What is a common method to merge two lists in Python?

A: One common method is to use the + operator for concatenation. For example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2

Q: Is there another method to merge lists without using the + operator?

A: Yes, the extend() method can be used to append elements from one list to another.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)

Q: How can I merge lists using list comprehension?

A: List comprehension provides a concise way to merge lists.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = [item for sublist in [list1, list2] for item in sublist]

Q: What is the time complexity of merging two lists using list comprehension?

A: The time complexity is O(n + m), where n and m are the lengths of the two lists being merged. List comprehension iterates over all elements in both lists to create the new merged list.

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details