GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Data Structures
  • Sets
  • AVINASH NETHALA
  • 4 years ago3 years ago
  • Previous: Bubble Sort algorithm in Python

This view

  • Original page
  • New address

GeezerVison is showing www.programminginpython.com — Set Operations in Python - Programming 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

 

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

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

B-A Venn diagram

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

 

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

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.

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • More
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to share on WhatsApp (Opens in new window) WhatsApp

Online Python Compiler

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • More
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to share on WhatsApp (Opens in new window) WhatsApp

Leave a Reply Cancel reply

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

Related Posts

Python Dictionary and its operations

Python Dictionary and its operations

AVINASH NETHALA4 years ago4 years ago 0
Python tuple operations – Add, Remove, Slice, Concat, Reverse

Python tuple operations – Add, Remove, Slice, Concat, Reverse

AVINASH NETHALA4 years ago3 years ago 0
Python program to merge or concatenate two lists

Python program to merge or concatenate two lists

AVINASH NETHALA6 years ago4 years ago 0
Python Program to find the Biggest and Smallest of 3 numbers using lists

Find the Biggest and Smallest of 3 numbers using lists in Python

AVINASH NETHALA8 years ago4 years ago 0

Recent Posts

  • Python vs R: Which Language is Better for Data Science?
  • Top 7 Python Books You Must Read in 2025
  • Best Python Web Frameworks: Django, Flask, and FastAPI Breakdown
  • 20 Best Python One-Liners to Boost Your Coding Skills
  • Matplotlib Data Visualization in Python

Suggested Courses

  • Complete Python Developer: Zero to Mastery.
  • Automate the boring stuff.
  • Python and Django Full Stack Web Developer Bootcamp.
  • Artificial Intelligence and Machine Learning E-Degree.
  • Complete Python & Python OOP.

Subscribe to our newsletter!

Great Deals

Ads
  • Health and Beauty
  • Deals on Electronics
  • Toys and Games
  • Sports and Outdoors
  • Pet Supplies
  • Shoes
  • Movies and TV

Categories

  • Algorithms (8)
  • Artificial Intelligence AI (3)
  • Basic Programs (25)
  • Books (1)
  • Data Structures (10)
  • Databases (1)
  • Dictionaries (1)
  • Files Handling (1)
  • Letter Patterns (26)
  • Lists (7)
  • Machine Learning (3)
  • Math Programs (6)
  • Pattern Programming (31)
  • Promoted (1)
  • Python for Automation (1)
  • Python for Data Science (6)
  • Python for Ethical Hacking (2)
  • Python For Finance (4)
  • Python GUI (5)
  • Python Libraries (6)
  • Python OOP (1)
  • Python Resources (3)
  • Python Tips and Tricks (10)
  • Searching Algorithms (2)
  • Sets (1)
  • Sorting Algorithms (6)
  • Tuples (1)
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.