AppDividend
Latest Code Tutorials

How to Merge Two Lists into One in Python

0

To merge the list in Python, use list comprehension. List comprehension is an artistic pythonic way to create lists based on extant lists. In our case, we have to merge a list based on two lists. Python List is an inbuilt data type that is an ordered and changeable collection, and it allows duplicate elements.

Merge Two Lists into One in Python

To merge two lists into one, use list comprehension. List Comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists.

The syntax for list comprehension is the following.

[expression for item in list]

Example

# app.py

name_list = ['Harry', 'Hermione', 'Ginny']
age_list = [17, 17, 16]

merged_list = [j for i in zip(name_list, age_list) for j in i]

print('Merged list', merged_list)

Output

Merged list ['Harry', 17, 'Hermione', 17, 'Ginny', 16]

List comprehensions can utilize conditional statements to modify the existing list (or other tuples).

From the output, you can see that we have merged two lists into one list and print that list.

Match the order of input

If the order of the elements much matches the order in your example, you can use the combination of the zip() and chain() methods.

The zip() method returns an iterator object. The chain() method makes an iterator that returns items from the first iterable until it is exhausted, then proceeds to the next iterable until all of the iterables are exhausted.

The first step is to import the itertools module and defined two lists.

# app.py

from itertools import chain

name_list = ['Harry', 'Hermione', 'Ginny']
age_list = [17, 17, 16]

Then use the combination of list(), chain(), zip(), and * operator to merge the two lists.

# app.py

from itertools import chain

name_list = ['Harry', 'Hermione', 'Ginny']
age_list = [17, 17, 16]

merged_list = list(chain(*zip(name_list, age_list)))

print('Merged list', merged_list)

Output

Merged list ['Harry', 17, 'Hermione', 17, 'Ginny', 16]

Merge two lists using for loop

Merging two lists using for loop is not a pythonic way, but I am showing how to merge lists in Python using for loop.

# app.py

name_list = ['Harry', 'Hermione', 'Ginny']
age_list = [17, 17, 16]

merged = []
for i in zip(name_list, age_list):
    for j in i:
        merged.append(j)

print(merged)

Output

['Harry', 17, 'Hermione', 17, 'Ginny', 16]

You can see that we got the merged list. That is it for the merging two lists into one in Python.

See also

Pandas DataFrame merge()

Python zip list of lists

Python zip dictionary

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.