Open In App

Python | Union of two or more Lists

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. 

Examples:

Maintained repetition only
Input : 
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
Output :
[23, 15, 2, 14, 14, 16, 20, 52, 2, 48, 
15, 12, 26, 32, 47, 54]

Maintained repetition and order
Input : 
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
Output :
[2, 2, 12, 14, 14, 15, 15, 16, 20, 23, 
26, 32, 47, 48, 52, 54]

Without repetition
Input : 
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
Output :
[32, 2, 12, 14, 15, 16, 48, 47, 20, 52, 54, 23, 26]

Union of three lists
Input : 
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
lst3 = [4, 78, 5, 6, 9, 25, 64, 32, 59]
Output :
[32, 64, 2, 4, 5, 6, 9, 12, 14, 15, 16, 
48, 47, 78, 20, 52, 54, 23, 25, 26, 59]

Maintaining Repetition

We can simply use the plus “+” operator inorder to combine two list into one. This will reflect the repetition. 

Python3




# Python program to illustrate union
# Maintained repetition
def Union(lst1, lst2):
    final_list = lst1 + lst2
    return final_list
 
# Driver Code
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
print(Union(lst1, lst2))


Output:

[23, 15, 2, 14, 14, 16, 20, 52, 2, 48, 15, 
12, 26, 32, 47, 54]

Time complexity: O(n), where n is the length of the longest list.

Auxiliary space complexity: O(n), where n is the total number of elements in both lists.

Maintaining both Repetition and Order

To maintain the order of appearance in the new list we need to use the sorted() function, passing the addition of two lists(plus operated, as in the previous problem) as parameters. 

Python3




# Python program to illustrate union
# Maintained repetition and order
def Union(lst1, lst2):
    final_list = sorted(lst1 + lst2)
    return final_list
 
# Driver Code
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
print(Union(lst1, lst2))


Output:

[2, 2, 12, 14, 14, 15, 15, 16, 20, 23, 26, 32, 47, 48, 52, 54]

The time complexity of the Union function is O(n log n), where n is the total number of elements in both lists. 

The space complexity of the Union function is O(n), where n is the total number of elements in both lists.

Without Repetition

To get rid of all the repetitive elements from the initial list, we use the set() function on both the lists, individually. Then we add them using the “+” operator and pass as a new list. 

Python3




# Python program to illustrate union
# Without repetition
def Union(lst1, lst2):
    final_list = list(set(lst1) | set(lst2))
    return final_list
 
# Driver Code
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
print(Union(lst1, lst2))


Output:

[32, 2, 12, 14, 15, 16, 48, 47, 20, 
52, 54, 23, 26]

More than two lists

We can also make an union of more than two lists. This can be done efficiently by using both the set() and union() function, simultaneously, as shown in the below example. This also takes care of the repetition and prevents them. 

Python3




# Python program to illustrate union
# Union of three lists
def Union(lst1, lst2, lst3):
    final_list = list(set().union(lst1, lst2, lst3))
    return final_list
 
# Driver Code
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
lst3 = [4, 78, 5, 6, 9, 25, 64, 32, 59]
print(Union(lst1, lst2, lst3))


Output:

[32, 64, 2, 4, 5, 6, 9, 12, 14, 15, 16, 
48, 47, 78, 20, 52, 54, 23, 25, 26, 59]

 Approach : Using extend() method

Step-by-step approach:

  • First, import the “collections” module in the Python program.
  • Define two lists: lst1 and lst2 which contain some integer values.
  • Use the extend() method to append all the elements of lst2 to lst1. Now, lst1 contains all the elements of both lst1 and lst2.
  • Use the print() function to display the combined list, lst1, which maintains the repetition of elements.
  • Use the set() function to create a set from lst1, which will not maintain the repetition of elements or the order of elements.
  • Use the list() function to convert the resulting set back into a list.
  • Use the print() function to display the new list, x, which does not maintain repetition or order.

Below is the implementation of the above approach:

Python3




# Python program to illustrate union
 
lst1 = [23, 15, 2, 14, 14, 16, 20, 52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
lst1.extend(lst2)
 
# Maintaining repetition
print("Maintaining repetition "+str(lst1))
 
# Not maintaining repetition and order
x = list(set(lst1))
print("Not maintaining repetition "+str(x))


Output

Maintaining repetition [23, 15, 2, 14, 14, 16, 20, 52, 2, 48, 15, 12, 26, 32, 47, 54]
Not maintaining repetition [32, 2, 12, 14, 15, 16, 48, 47, 20, 52, 54, 23, 26]

 Approach : Using itertools

The itertools module has functions for working with iterable data structures in Python. One of its functions is chain() function which can be used to concatenate two or more lists together.

Algorithm:

  • Import the itertools module.
  • Use the chain() function from the itertools module to concatenate two or more lists into one list.
  • Use the set() function to remove duplicates and convert the concatenated list to a set
  • Convert the set back to a list and return it as the final union
    Return the concatenated list.

Example code to concatenate two lists using chain():

Python3




# import the itertools module
import itertools
 
# define the function to find the union of two or more lists
def union_lists(*lists):
     
    # use the chain() function from itertools to concatenate all the lists
    concatenated_list = list(itertools.chain(*lists))
     
    # use the set() function to remove duplicates and convert the concatenated list to a set
    unique_set = set(concatenated_list)
     
    # convert the set back to a list and return it as the final union
    final_union = list(unique_set)
    return final_union
 
# Example usage of the function
list1 = [23, 15, 2, 14, 14, 16, 20 ,52]
list2 = [2, 48, 15, 12, 26, 32, 47, 54]
list3 = [4, 78, 5, 6, 9, 25, 64, 32, 59]
 
# Find the union of three lists
print(union_lists(list1, list2, list3))


Output

[2, 4, 5, 6, 9, 12, 14, 15, 16, 20, 23, 25, 26, 32, 47, 48, 52, 54, 59, 64, 78]

The time complexity of the union_lists() function is O(n), where n is the total number of elements in all input lists.
The auxiliary space of the union_lists() function is O(n), where n is the total number of elements in all input lists, due to creating a concatenated list and a set of unique elements.



Previous Article
Next Article

Similar Reads

Python | Union of Value Lists
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the union of lists which are in form of keys of dictionary. Let's discuss certain ways to solve this type of problem. Method #1 : Using Loops Using loops is a naive brute force approach to perform this particu
8 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Indexing Lists Of Lists In Python
Lists of lists are a common data structure in Python, providing a versatile way to organize and manipulate data. When working with nested lists, it's crucial to understand how to index and access elements efficiently. In this article, we will explore three methods to index lists of lists in Python using the creation of a sample list, followed by ex
3 min read
Python | Union Operation in two Strings
One of the string operation can be computing the union of two strings. This can be useful application that can be dealt with. This article deals with computing the same through different ways. Method 1 : Naive Method The task of performing string union can be computed by naive method by creating an empty string and checking for new occurrence of ch
5 min read
Find the union of two NumPy arrays
To find union of two 1-dimensional arrays we can use function numpy.union1d() of Python Numpy library. It returns unique, sorted array with values that are in either of the two input arrays. Syntax: numpy.union1d(array1, array2) Note The arrays given in input are flattened if they are not 1-dimensional. Let's see examples of how to find union of tw
2 min read
Python set operations (union, intersection, difference and symmetric difference)
This article demonstrates different operations on Python sets. Examples: Input : A = {0, 2, 4, 6, 8} B = {1, 2, 3, 4, 5} Output : Union : [0, 1, 2, 3, 4, 5, 6, 8] Intersection : [2, 4] Difference : [8, 0, 6] Symmetric difference : [0, 1, 3, 5, 6, 8] In Python, below quick operands can be used for different operations. | for union. & for interse
1 min read
Union() function in Python
Python set Union() Method returns a new set that contains all the items from the original set. The union of two given sets is the set that contains all the elements of both sets. The union of two given sets A and B is a set that consists of all the elements of A and all the elements of B such that no element is repeated. The symbol for denoting uni
3 min read
Python | Pandas Index.union()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.union() function form the union of two Index objects and sorts if possible. The function follows behaves like a standard se
2 min read
Practice Tags :
three90RightbarBannerImg