Python set operations: union, intersection and difference - with 10 examples (2023)

Stuck trying to use Python set operations? Do you want to know how to use them? This tutorial gives you a basic understanding of set operations in Python.

In this tutorial, we'll look at set operations in Python and other operations performed on sets. In addition, we look at the different methods for sets and examples of set operations in Python. look at thatArticle for a deeper dive into combinatorics with Python.

A set is a collection of unordered elements. Each element must be unique and immutable. However, a lot itself is changeable.

You can add or remove items from sets. You can also perform mathematical operations on them such as B. Union, intersection and difference.

The concept of a set has been explicitly translated from mathematics into programming languages ​​like Python. With that have come some extremely helpful methods, such as:Union(),Overlap(), AndDifference(), also directly translated from mathematics.

Sets are not simply a fundamental concept in mathematics. During your programming career, you will likely encounter a variety of challenges that can be solved much more quickly by using sets.

If you are an absolute beginner in Python, we recommend you give it a trythis track. If you are a beginner with some Python knowledge, check out the coursePython Basics Part 3, which covers the basics of variables, lists, conditional statements, loops, and functions.

(Video) Set in Python Operations : Union,Intersection,Difference & Symmetric difference

Sets and set operations in Python

A set is defined by enclosing each element (i.e. elements) in braces and separating them with a comma or using the built-inSentence()Method. It can contain an unlimited number of elements of different categories (integer, float, tuple, string, etc.).

However, a sentence cannot contain modifiable elements such as lists, sentences, or dictionaries. Visit this article toLearn about the differences between lists, tuples, and sets.LearnPython.comis an incredible platform to help you get started with Python.

Empty sets can be a little tricky to use in Python. In Python, empty braces result in an empty dictionary; However, we cannot use them to initialize an empty set. Instead we use theSentence()Function with no arguments to create a set with no elements.

Check out the following code to understand these concepts:

# A set of integersint_set = {10, 20, 30, 40, 50}# A set of mixed data types mixed_set = {9, "This is a set item", (1, 2)}# All set items are uniquemy_set = { 1, 2 , 3, 1, 3, 3}print(my_set) # Output: {1, 2, 3}# From a listmy_set = set([1, 2, 3, 2, 4, 5 , 5])print(my_set) # Output: {1, 2, 3, 4, 5}

Modifying a set in Python

Indexing and partitioning cannot be used to access or update an element of a set. The set data type does not support this because sets are not ordered.

Theadd to()method is used to add a single element, and theTo update()method is used to update multiple components. Tuples, lists, strings, and other sets can be passed toTo update()Method. Duplicates are avoided at all costs.

The following code illustrates these examples.

(Video) Python Programming 62 - Union and Intersection - Set Operations

# Set initializemy_set = {11, 60}# Add an item to the set# Output: {11, 21, 60}my_set.add(21)print(my_set)# Add more than one item to the set# Output: { 8, 11 , 13, 20, 21, 60}my_set.update([20, 13, 8])print(my_set)

Remove items from a set

The methodsdiscard()Andremoved()are used to delete a specific element from a set. They are identical with only one difference. Thediscard()method leaves the set unchanged if the item does not exist in the set. Theremoved()method, on the other hand, returns an error if the item is not present in the set.

The use of these functions is demonstrated in the following example.

# Initialize a setmy_set = {10, 20, 30, 40, 50}print(my_set)# Discard an elementmy_set.discard(40)print(my_set) # Output: {10, 20, 30, 50}# Remove an elementmy_set. remove(60) # Key error!

We can use those tooPop()Method of removing and returning an item. However, there is no way of knowing which element will be inserted since the set is an unordered data type. It's absolutely random!

Note that theclear()Method is used to delete all elements from a set.

# Initialize a setmy_set = set("LearnPython")# Pop an element print(my_set.pop()) # Output: random element# Clear setmy_set.clear() print(my_set) # Output: set()

In Python, most, but not all, set operations are performed in one of two ways: by an operator or by a method. Before we look at how different set operations work in Python, it's important to understand the difference between an operator and a method.

In Python, a method is similar to a function except that it is bound to an object. When we invoke a method on an object, it may or may not affect that object—a set, in this case. It's worth noting that each operator corresponds to a specific Python special function. So they both accomplish the same thing, but have different syntax requirements.

Python supports many set operations including union, intersection, difference, and symmetric difference. Let's look at some examples of set operations in Python.

(Video) Python set operations union, intersection, difference, symmetric_difference & updating the main set

Python union operation with example

The union of two sets is the set of all elements without duplicates that are in either or both sets. In Python you can either use theUnion()method or the|Syntax to find the union. Let's look at a Python union example.

Use of|Operator:

# define the two sets first_set = {1, 5, 7, 4, 5}second_set = {4, 5, 6, 7, 8}# create the union of the two sets new_set = first_set | second_setprint(new_set) # output: {1, 2, 3, 4, 5, 6, 7, 8}

Running the above code will create two sets:first setAndsecond_set. Then the union operator creates anew_setwith all the unique elements from thefirst setand thesecond_set.

The same is achieved with theUnion()Method:

new_set = first_set.union(second_set)

Since the union consists of the elements of both sets, it is symmetric. So,first_set.union(second_set)gives the same sentence assecond_set.union(first_set).

Python intersection operation with example

The intersection of two sets is the set of all elements common to both sets. In Python you can either use theOverlap()method or the & operator to find the intersection. Here are some examples of Python cuts:

Using the & operator:

(Video) Set operation in Python || Python Set (Union, Intersection, Difference & Symmetric difference)

# define the two setsfirst_set = {1, 5, 7, 4, 5}second_set = {4, 5, 6, 7, 8}# create the intersection of the two setsnew_set = first_set & second_setprint(new_set) # output: {4 , 5}

Running the above code will create two sets:first setAndsecond_set. Then the intersection operator produces anew_setwith all the unique elements from thefirst setand thesecond_set.

The same is achieved with theOverlap()Method:

new_set = first_set.intersection(second_set)

Because the intersection method produces a set of elements common to both sets, it is symmetric. So,first_movement.intersection(second_movement)gives the same sentence assecond_movement.intersection(first_movement).

Python Set Difference Operation with example

The difference between the two sets is the set of all elements that are present in the first set but not in the second. With Python you can either use theDifference()method or operator to do this. Let's look at some examples of Python set differences.

Using the - operator:

# Definition of the two setsfirst_set = {1, 5, 7, 4, 5}second_set = {4, 5, 6, 7, 8}# Formation of the difference between the two setsnew_set = first_set - second_setprint(new_set) # Output: {1 , 2, 3}

You can also use theDifference()Method:

# Initialize difference of two sets# A and Bfirst_set = {1, 2, 3, 4, 5}second_set = {4, 5, 6, 7, 8}# Create difference between the two setsnew_set = second_set.difference(first_set) print( new_set) # output: {6, 7, 8}

As shown in the example, theDifference operator is not symmetric. Which quantity you name first is important and influences the outcome of thenew_set.

(Video) set operations | union | intersection | difference | symmetric_difference python

Leverage Python set operations

In this tutorial you learned how to define set operations in Python. We also became familiar with the functions, operators, and methods used to work with sets. If you want to learn more about Python sets, e.g. B. How to get the symmetric difference visit the article “Python Set Operations and More: Everything you need to know about Python sets.“

Videos

1. Set Operations in Python - Beginner Python - Programming Tutorial
(Misha Sv)
2. Set Operations in Python [P20] | With Examples
(J's Lab)
3. Program To Perform Set Operation Like Maths In Python - Find Union, Intersection, Difference
(Tech Programming CS IT)
4. Python Join Sets Using Update, Union, Intersection and Symmetric Difference | Code Myth
(Code Myth)
5. Easy TRICK to get Union, Intersection and Difference in Python 🧮 #python #coding #programming
(Code Cyborg)
6. Python set.intersection() & "&" & Explanations & Examples & Runtime
(Finxter - Create Your Six-Figure Coding Business)
Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated: 02/05/2023

Views: 5815

Rating: 4.4 / 5 (45 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.