Home » Set Operations in Python

Set Operations in Python

Set Operations in Python

Hello everyone, welcome back to programminginpython.com. Here in this post, I am going to discuss another data type in Python called SET, which is an unordered collection of data that is iterable and has no duplicate elements. The set in Python represents the mathematical notation of a set.

A set can be simply initialized as example = set(), here example is the name of the set, and can also put some elements in it like example = set(['one', 2, 'three']) and here in set datatype, the order of the elements is not preserved, which means lists and tuples where the order of the elements is checked for indexing.

Now I will perform some of the operations on sets. So let’s get started.

You can also watch the video on YouTube here

Program on GitHub

Add elements to set

One can add elements to set directly as set(['one',1,'two',2]) or there is a method called add as example.add('one') where example here is a set example = set()

Here in this example, I will add even, odd, prime, and composite numbers between 1 to 10 as different set elements.

Initialize the sets,

# set of all numbers from 1 to 10
numbers = set()

# set of all even numbers between 1 to 10
even_numbers = set()

# set of all odd numbers between 1 to 10
odd_numbers = set()

# set of all prime numbers between 1 to 10
prime_numbers = set()

# set of all composite numbers between 1 to 10
composite_numbers = set()

Now I will add elements to these sets, here I can manually add elements to the set as explained before numbers = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) but I will do it programmatically here, in the previous tutorials I said how to find even, odd, prime, and composite numbers, so I will use that logic to add elements to the respected set here.

for i in range(1, 11):
    numbers.add(i)
    even_odd_sets(i)
    prime_composite_sets(i)

functions for even_odd_sets and prime_composite_sets

# function which finds even and odd numbers
def even_odd_sets(num):
    if num % 2 == 0:
        even_numbers.add(num)
    else:
        odd_numbers.add(num)


# function which finds prime and composite numbers
def prime_composite_sets(num):
    if num > 1:
        for j in range(2, num):
            if (num % j) == 0:
                composite_numbers.add(num)
                break
        else:
            prime_numbers.add(num)

Program on GitHub

Length of a set

Python has an inbuilt function len(set) for finding the length of a set. So I will find the length of the above 5 sets which have different types of numbers in them.

# Length of the set

print("Length of set numbers:",
      len(numbers))

print("Length of set even numbers:",
      len(even_numbers))

print("Length of set odd numbers:",
      len(odd_numbers))

print("Length of set prime numbers:",
      len(prime_numbers))

print("Length of set composite numbers:",
      len(composite_numbers))

The above lines produce the following output,

Set Operations in Python
Set Operations in Python

 

Intersection of sets

Intersection means the common elements in any given 2 sets, it is generally denoted as ? in mathematics, assume A and B are 2 sets, then consider the following diagram where A ? B are the common elements in both sets.

Set Operations in Python
Set Operations in Python

So we can implement that intersection operation in Python by using the intersection method on one set with the other set. Ex: A.intersection(B)==> A ? B

I will apply this to the numbers example I am using for this tutorial.

# Intersection of sets

print("\n\nIntersection of numbers and even_numbers:",
      numbers.intersection(even_numbers))

print("Intersection of numbers and odd_numbers:",
      numbers.intersection(odd_numbers))

print("Intersection of numbers and prime_numbers:",
      numbers.intersection(prime_numbers))

print("Intersection of numbers and composite_numbers:",
      numbers.intersection(composite_numbers))

print("Intersection of prime numbers and composite_numbers:",
      prime_numbers.intersection(composite_numbers))

Union of sets

Union of any 2 sets returns all the elements in both the sets, it is generally denoted as ? in mathematics, assume A and B are 2 sets, then consider the following diagram where A ? B are all the elements in both the sets.

So I will implement this union operation in python by using a function called union(), Ex: A.union(B)

Now I will apply this to our numbers example.

# Union of sets

print("\n\nUnion of numbers and even_numbers:",
      numbers.union(even_numbers))

print("Union of numbers and odd_numbers:",
      numbers.union(odd_numbers))

print("Union of prime numbers and composite_numbers:",
      prime_numbers.union(composite_numbers))

Difference between sets

The difference between the two sets is all the elements in the first set are not in the second.

A – B is the Set of all elements in A but not in B

B – A is the Set of all elements in B but not in A

See the below Venn diagrams,

A-B Venn diagram

Set Operations in Python
Set Operations in Python

B-A Venn diagram

Set Operations in Python
Set Operations in Python

 

This is implemented in Python by using a function called difference(), Ex: A.difference(B) is the notation for A-B

Now I will implement our numbers example.

# Difference of sets

print("\n\nDifference between numbers and prime_numbers:",
      numbers.difference(prime_numbers))

print("Difference between prime_numbers and numbers:",
      prime_numbers.difference(numbers))

If you observe the above output, the difference between numbers and prime_numbers gave all the elements in numbers set which are not in prime_numbers set and the difference prime_numbers and numbers returned an empty set because there are no elements in prime_numbers which are not in numbers.

Program on GitHub

Remove an element from a set

We can also remove a single element. There are two functions for doing it remove() and discard()

Ex: set.remove('element')

Ex: set.discard('element')

The difference between these two functions remove and discard is that, if the element we are deleting is not present, then the remove function throws an error whereas the discard function, just removes if the element is present or else does nothing.

example = set(['test', 43, 'another', 120])
print("\nExample Set:", example)

# Remove element in a set
example.remove(120)
print(example)

example.discard(43)
print(example)

 

Set Operations in Python
Set Operations in Python

 

Clear all the elements

And finally, we can clear all the elements in a set by using an inbuilt function in Python for sets called clear().Simply call this method on any set and all the elements in it will be cleared and will become empty.

example = set(['test', 43, 'another', 120])
print("\nExample Set:", example)

# Clear the set
example.clear()
print(example)

 

Set Operations in Python
Set Operations in Python

Program on GitHub

That’s it for this post guys, also feel free to check the programs on patterns here or find some programs on algorithms here.

Online Python Compiler

Leave a Reply

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