Concatenate two elements in a list Python

The join() string method returns a string by joining all the elements of an iterable (list, string, tuple), separated by a string separator.

Example

text = ['Python', 'is', 'a', 'fun', 'programming', 'language']

# join elements of text with space print(' '.join(text))

# Output: Python is a fun programming language

Syntax of String join()

The syntax of the join() method is:

string.join(iterable)

joint() Parameters

The join() method takes an iterable (objects capable of returning its members one at a time) as its parameter.

Some of the example of iterables are:

Note: The join() method provides a flexible way to create strings from iterable objects. It joins each element of an iterable (such as list, string, and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.

Return Value from join() method

The join() method returns a string created by joining the elements of an iterable by string separator.

If the iterable contains any non-string values, it raises a TypeError exception.

Example 1: Working of the join() method

# .join() with lists numList = ['1', '2', '3', '4'] separator = ', '

print(separator.join(numList))

# .join() with tuples numTuple = ('1', '2', '3', '4')

print(separator.join(numTuple))

s1 = 'abc' s2 = '123' # each element of s2 is separated by s1 # '1'+ 'abc'+ '2'+ 'abc'+ '3'

print('s1.join(s2):', s1.join(s2))

# each element of s1 is separated by s2 # 'a'+ '123'+ 'b'+ '123'+ 'b'

print('s2.join(s1):', s2.join(s1))

Output

1, 2, 3, 4 1, 2, 3, 4 s1.join(s2): 1abc2abc3 s2.join(s1): a123b123c

Example 2: The join() method with sets

# .join() with sets test = {'2', '1', '3'} s = ', '

print(s.join(test))

test = {'Python', 'Java', 'Ruby'} s = '->->'

print(s.join(test))

Output

2, 3, 1 Python->->Ruby->->Java

Note: A set is an unordered collection of items, so you may get different output (order is random).

Example 3: The join() method with dictionaries

# .join() with dictionaries test = {'mat': 1, 'that': 2} s = '->' # joins the keys only

print(s.join(test))

test = {1: 'mat', 2: 'that'} s = ', ' # this gives error since key isn't string

print(s.join(test))

Output

mat->that Traceback (most recent call last): File "...", line 12, in <module> TypeError: sequence item 0: expected str instance, int found

The join() method tries to join the keys (not values) of the dictionary with the string separator.

Note: If the key of the string is not a string, it raises a TypeError exception.

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

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.

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 3
0000
1111
2222
3333
4444
5555
6666
7777
8888
9999

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