Python Programming

Mastering List Unions in Python

Spread the love

Python offers several ways to combine lists, depending on whether you want to keep duplicate entries and whether the order matters. This guide explores various techniques to efficiently handle list unions.

Table of Contents

Union with Duplicate Elements

The simplest way to combine two lists, preserving all elements and their repetitions, is using the + operator:


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

union_list = list1 + list2
print(union_list)  # Output: [1, 2, 2, 3, 3, 4, 2]

Sorted Union

For a sorted union, combine the + operator with the sorted() function:


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

union_list = sorted(list1 + list2)
print(union_list)  # Output: [1, 2, 2, 2, 3, 3, 4]

Union without Duplicate Elements

To create a union without duplicates, use sets:


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

union_set = set(list1) | set(list2)  # or set(list1).union(list2)
union_list = list(union_set)  # Convert back to a list if needed
print(union_list)  # Output: [1, 2, 3, 4] (order may vary)

Sets automatically remove duplicates. Note that the order of elements in the resulting list might not be the same as in the original lists.

Union of Multiple Lists

For more than two lists, the set approach remains efficient:


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

union_set = set(list1) | set(list2) | set(list3)
union_list = list(union_set)
print(union_list)  # Output: [1, 2, 3, 4, 5, 6] (order may vary)

#More scalable solution using reduce:
from functools import reduce
union_list = list(reduce(lambda x,y: x | y, [set(l) for l in [list1, list2, list3]]))
print(union_list) # Output: [1, 2, 3, 4, 5, 6] (order may vary)

The reduce function provides a more concise and scalable solution for many lists. Remember that the order of elements might not be preserved; use sorted() if order is important.

Leave a Reply

Your email address will not be published. Required fields are marked *