Python combine two lists side by side

I am looking for the shortest way of doing the following [one line solution]

a = ["a", "b", "c"]
b = ["w", "e", "r"]

I want the following output:

q = ["a w", "b e", "c r"]

Of course this can be achieved by applying a for loop. But I am wondering if there is a smart solution to this?

Anand S Kumar

84.8k18 gold badges178 silver badges169 bronze badges

asked Aug 10, 2015 at 9:17

1

You can use str.join[] and zip[] , Example -

q = [' '.join[x] for x in zip[a,b]]

Example/Demo -

>>> a = ["a", "b", "c"]
>>> b = ["w", "e", "r"]
>>> q = [' '.join[x] for x in zip[a,b]]
>>> q
['a w', 'b e', 'c r']

answered Aug 10, 2015 at 9:18

Anand S KumarAnand S Kumar

84.8k18 gold badges178 silver badges169 bronze badges

You can use zip within a list comprehension :

>>> ['{} {}'.format[*i] for i in zip[a,b]]
['a w', 'b e', 'c r']

answered Aug 10, 2015 at 9:18

MazdakMazdak

102k17 gold badges156 silver badges181 bronze badges

More pythonic way;

b = map[' '.join,zip[a,b]]

answered Aug 10, 2015 at 9:37

1

a = ["a", "b", "c"]
b = ["w", "e", "r"]

print[["{} {}".format[_a ,_b] for _a,_b in zip[a,b]]]
['a w', 'b e', 'c r']

answered Aug 10, 2015 at 9:18

0

one line solution:

[aa+" "+bb for aa,bb in zip[a,b]]

output:

['a w', 'b e', 'c r']

one liner without zip:

[a[i]+" "+b[i] for i in range[len[a]]]

output:

['a w', 'b e', 'c r']

answered Aug 10, 2015 at 9:18

The6thSenseThe6thSense

7,7436 gold badges30 silver badges63 bronze badges

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.

Example

Join two list:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print[list3]

Try it Yourself »

Another way to join two lists are by appending all the items from list2 into list1, one by one:

Example

Append list2 into list1:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

for x in list2:
  list1.append[x]

print[list1]

Try it Yourself »

Or you can use the extend[] method, which purpose is to add elements from one list to another list:

Example

Use the extend[] method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend[list2]
print[list1]

Try it Yourself »


Python Lists are used to multiple items in one variable. Lists are changeable, ordered and it also allows duplicate values. The values are enclosed in square brackets.

You can concatenate Lists to one single list in Python using the + operator.

In this tutorial, you’ll learn the different methods available to concatenate lists in python and how the different methods can be used in different use-cases appropriately.

If You’re in Hurry…

You can use the below code snippet to concatenate two lists in Python.

Snippet

odd_numbers = [1, 3, 5, 7, 9] 

even_numbers = [2, 4, 6, 8, 10] 

numbers = odd_numbers + even_numbers 


print["Concatenated list of Numbers : \n \n" + str[numbers]] 

+ operator concatenates the two lists and creates a new list object as a resultant object.

Output

    Concatenated list of Numbers : 

    [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

If You Want to Understand Details, Read on…

In this tutorial, you’ll learn the different methods available to join multiple lists to one list object.

  • Using + Operator
  • Using Extend[]
  • Using Append[]
  • Using * Operator
  • Using List Comprehension
  • Using Itertools.chain[]
  • Concatenate List of Lists
  • Merge Lists Only Unique Items
  • Concatenate Two Lists Side By Side
  • Combine Lists into Dataframe
  • Conclusion
  • You May Also Like

Using + Operator

You can join two or multiple list objects into one list object using the + operator.

Plus operator is normally used to sum the two operands used in it. In the context of a list, it acts as a concatenation operator where it adds the items of the two lists and produces one resultant list object.

Use-case: You can use this method when you want to create a new list object rather than adding the items of one list into the existing list. This is also the fastest method for concatenating lists.

Snippet

odd_numbers = [1, 3, 5, 7, 9] 

even_numbers = [2, 4, 6, 8, 10] 

numbers = odd_numbers + even_numbers 

print["Concatenated list of Numbers : \n \n" + str[numbers]] 

You’ll see the two lists odd_numbers and even_numbers concatenated into a single list called numbers.
Output

    Concatenated list of Numbers : 

    [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

This is how you can use the + operator to concatenate two lists and create a new resultant object.

Using Extend[]

You can use the extend[] method to extend an existing list with one or more additional items. It increases the length of the list by the number of elements passed to the method.

For example, if you pass 5 elements to the extend[] method, then it’ll add those 5 elements to the existing list.

Use-Case: You can use this method if you want to add more than one element to an existing list at one shot.

Snippet

odd_numbers = [1, 3, 5, 7, 9] 

even_numbers = [2, 4, 6, 8, 10] 

odd_numbers.extend[even_numbers]

print["Concatenated list of Numbers : \n \n" + str[odd_numbers]] 

You can see all the items on the list even_numbers is added to the existing list odd_numbers at one shot using the odd_numbers.extend[even_numbers] statement.

Output

    Concatenated list of Numbers : 

    [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

This is how you can concatenate two lists using the extend[] method.

Using Append[]

You can use the append[] method to add one element at a time to an existing list. It increases the length of the existing list by one at a time.

You cannot add more than one item at once using the append[] method.

If you want to add more than one item using append[], you need to use the for loop to append each item.

This doesn’t create a new resultant object. It only appends items to the existing list object.

Use-Case: You can use this method if you want to add only one element to an existing list.

Snippet

odd_numbers = [1, 3, 5, 7, 9] 

even_numbers = [2, 4, 6, 8, 10] 

for i in even_numbers:
    odd_numbers.append[i]

print["Concatenated list of Numbers : \n \n" + str[odd_numbers]] 

You can see that all the items in the even_numbers list are added to the list odd_numbers using the append[] method one by one.

Output

    Concatenated list of Numbers : 

    [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

This is how you can concatenate two lists using the append[] method.

Using * Operator

* operator is python unpacks the items in the collections into a positional argument. This is introduced in the version 3.6.

You can check the python version using the below script.

Script

import sys
print[sys.version]

Output

3.8.2 [default, Sep  4 2020, 00:03:40] [MSC v.1916 32 bit [Intel]]

If your version is greater than or equal to version 3.6, then you can use this method.

When you use the * operator in a list, it unpacks the elements in the list so that you can use the items directly. You need not iterate over the list again to access the item.

You can concatenate multiple lists into one list by using the * operator.

For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object.

Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot.

Snippet

zero = [0]

odd_numbers = [1, 3, 5, 7, 9] 

even_numbers = [2, 4, 6, 8, 10] 

numbers = [*zero, *odd_numbers, *even_numbers] 

print["Concatenated list of Numbers : \n \n" + str[numbers]] 

You can see the lists zero, odd_numbers and even_numbers concatenated into one single list object.

Output

    Concatenated list of Numbers : 

    [0, 1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

This is how you can concatenate multiple list objects into one single list object using the * operator.

Using List Comprehension

List comprehension provides a short syntax to create a new list based on the values in the existing list. You can also use list comprehension to concatenate two lists into one single list object.

You need to use two for loops in list comprehension to concatenate two lists into one.

Example: y for x in [odd_numbers, even_numbers] for y in x
where,

  • for x in [list_1, list_2]For loop to iterate over two lists one by one by one and add the result to a variable x
  • for y in x – To iterate over the result variable x and create a new list out of the list comprehension.

Use the below snippet to concatenate two lists into a single list using the list comprehension.

Snippet

odd_numbers = [1, 3, 5, 7, 9] 

even_numbers = [2, 4, 6, 8, 10] 

numbers = [y for x in [odd_numbers, even_numbers] for y in x]

print["Concatenated list of Numbers : \n \n" + str[numbers]] 

You can see the lists odd_numbers and even_numbers concatenated into a single list called numbers.

Output

    Concatenated list of Numbers : 

    [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

This is how you can concatenate lists in python using list comprehension.

itertools.chain[] chains the iterable arguments into one single iterable object.

A list is an iterable object. Hence, when you pass two lists into the chain[] method, it’ll chain the two iterable lists into once.

You need to import the itertools package using the statement import itertools statement.

Usecase: You can use this method when you want to iterate the concatenated list only once and do not want to store the concatenate list for future use.

In the below example, for demonstration purposes, a new list is created out of the chained list returned by itertools.chain[] method by passing it to the list[] method.

Snippet

import itertools

odd_numbers = [1, 3, 5, 7, 9] 

even_numbers = [2, 4, 6, 8, 10] 

numbers = list[itertools.chain[odd_numbers, even_numbers]] 

print["Concatenated list of Numbers : \n \n" + str[numbers]] 

You can see the two lists are concatenated into one list called numbers.

Output

    Concatenated list of Numbers : 

    [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

This is how you can concatenate multiple lists using the itertools.chain[] method when you want to use the concatenated list only once.

These are the different methods available to concatenate lists in python.

Now, you’ll learn how these different methods can be applied in various use-cases.

Concatenate List of Lists

Lists of lists in python is where a list item consists of another list. You can concatenate such a list of lists using the itertools.chain.fromiterable[] method.

Use the below snippet to concatenate the list of lists into one single object.

The list contains one list ['a', 'b'] as one object and just 'c' as another object. When you use it with itertools, all three items will be concatenated to another single list.

Snippet

import itertools

listoflists = [['a','b'], ['c']]

print[list[itertools.chain.from_iterable[listoflists]]]

Output

    ['a', 'b', 'c']

This is how you can concatenate a list of lists in python using the itertools[] method.

Merge Lists Only Unique Items

You can merge two lists into one single list with only unique items in it. This method can be used when you want to create a single list with unique items and removing the duplicates.

You can use the set[] method because python set[] is used to create a list of items with unique objects. It doesn’t allow duplicates.

Hence when you pass a list to a set, it removes the duplicates automatically.

Concatenate two lists using the + operator and pass the resultant list to the set[] method to remove duplicates. Then to create a list with unique items, you can pass the set to the list[] method.

Use the below snippet to merge lists only with unique items. Both the source list contains 0 in it. Hence this needs to be removed while merging two lists.

Snippet

odd_numbers = [0, 1, 3, 5, 7, 9] 

even_numbers = [0, 2, 4, 6, 8, 10]

numbers = list[set[odd_numbers + even_numbers]]

print["Concatenated list of Numbers [Only Unique Values] : \n \n" + str[numbers]] 

You can see the duplicate element 0 is available only once in the resultant list.

Output

    Concatenated list of Numbers [Only Unique Values] : 

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This is how you can join the list only with the unique elements.

Concatenate Two Lists Side By Side

During the normal concatenation operation, all the items in the second list are appended to the items in the first list, and so on. Hence the order of the elements in each list appears the same.

At times, you may need to concatenate items from each list side by side or element-wise.

For Example, you need to add the first elements of the list first, then the second element of the list to be added, then the third element of the list is added, and so on.

You can do this by using the list comprehension and zip[] function.

Zip[] function is used to create an iterator of tuples with the first item of each iterator is paired together, then the second item of the iterator is paired together, then the third item, and so on.

Then you can use the join[] method to join together all the paired tuples to one single list.

Use the below snippet to concatenate two lists side by side to create an order of numbers.

Snippet

odd_numbers = ['1', '3', '5', '7', '9'] 

even_numbers = ['2', '4', '6', '8', '10']

numbers = [' '.join[x] for x in zip[odd_numbers,even_numbers]]

print["Concatenated list of Numbers Side By side : \n \n" + str[numbers]] 

You can see the list created with the odd numbers and even numbers merged in order.

Output

    Concatenated list of Numbers Side By side : 

    ['1 2', '3 4', '5 6', '7 8', '9 10']

This is how you can concatenate two lists side by side or element-wise.

Combine Lists into Dataframe

You can combine more than one list into a dataframe using the pd.Dataframe[] method.

You need to import the pandas package using the statement import pandas as pd.

Use the zip[] method to create a row with one element from each list.

Then create a list of objects with rows using the list[] method.

Use the below snippet to combine two or more lists into a dataframe.

Snippet

import pandas as pd

list1 = range[10]
list2 = range[10]
list3 = range[10]

df = pd.DataFrame[list[zip[list1, list2, list3]],columns=['List 1', 'List 2', 'List 3']]

df

Where,

  • list1 = range[10] – To create sample lists with range of values till 10. three such lists are created to create a dataframe.
  • zip[list1, list2, list3] – Creates a row with one item from each list
  • list[zip[list1, list2, list3]] – Creates a List of rows from the values returned by zip
  • columns=['List 1', 'List 2', 'List 3'] – Names for the columns in the dataframe
  • pd.DataFrame[] – Method to create a dataframe with the passed list of values
  • df – Name of the dataframe to be created

Dataframe Will Look Like

List 1List 2List 30123456789
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9

This is how you can combine two or more lists into a dataframe using the pd.dataframe[] and zip[] method.

Conclusion

To summarize, you’ve learned the different methods available to concatenate lists in python. Also, you’ve learned when to use the different methods based on the different use cases such as

  • Concatenating lists
  • Concatenating lists of lists
  • Merging list only with unique items
  • Concatenate lists side by side

If you have any questions, comment below.

You May Also Like

  • Python List To String – Definitive Guide
  • How To Check If A Value Exists In A List In Python [Speed Compared]
  • How to Remove an element from a List Using Index in Python
  • How to Write a List To a File in Python

How do you merge two lists in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

Can you append two lists in Python?

Python's extend[] method can be used to concatenate two lists in Python. The extend[] function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

Can we concatenate two lists how?

The most conventional method to perform the list concatenation, the use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation. List comprehension can also accomplish this task of list concatenation.

How do I merge two nested lists in python?

Method 2: List comprehension.
Create a variable to store the input list of lists[nested list]..
Use the list comprehension to create a new list by joining all the elements of the nested list..

Chủ Đề