Table of Contents
ToggleIn Python, a set is an unordered collection of items. The items may be of different types. However, an item in the set must be an immutable object. It means we can only include numbers, strings, and tuples in a set and not lists. Python’s set class has different provisions to join set objects.
Joining sets in Python refers to merging two or more sets into a single set. When you join sets, you merge the elements of multiple sets while ensuring that duplicate elements are removed, as sets do not allow duplicate elements.
This can be achieved using various methods, such as union, update, set comprehension, set concatenation, copying, and iterative addition.
The “|” symbol (pipe) is defined as the union operator. It performs the A∪B operation and returns a set of items in A, B, or both. Sets don’t allow duplicate items.
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
s3 = s1 | s2
print(s3)
{1, 2, 3, 4, 5, 6, 7, 8}
The set class has a union() method that performs the same operation as the “|” operator. It returns a set object that holds all items in both sets, discarding duplicates.
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
s3 = s1.union(s2)
print(s3)
{1, 2, 3, 4, 5, 6, 7, 8}
The update() method also joins two sets like the union() method. However, it doesn’t return a new set object. Instead, the elements of the second set are added to the first, with duplicates not allowed.
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
s1.update(s2)
print(s1)
{1, 2, 3, 4, 5, 6, 7, 8}
In Python, the “*” symbol is used as the unpacking operator. The unpacking operator internally assigns each element in a collection to a separate variable.
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
s3 = {*s1, *s2}
print(s3)
{1, 2, 3, 4, 5, 6, 7, 8}
Set comprehension in Python is a concise way to create sets using an iterable, similar to list comprehension but resulting in a set instead of a list.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
joined_set = {x for s in [set1, set2] for x in s}
print(joined_set)
{1, 2, 3, 4, 5}
Iterative addition in the context of sets refers to iteratively adding elements from one set to another set using a loop.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
joined_set = set()
for element in set1:
joined_set.add(element)
for element in set2:
joined_set.add(element)
print(joined_set)
{1, 2, 3, 4, 5}
