Python set union intersection

Set Difference Python Intersection, union and difference of Sets in Python.

We are going to do this using Python (3.7), because it rules!

So, let’s dive right into it.

Some basic understanding of sets.

Sets are data structures that, based on specific rules they define, provide certain cool operations and guarantees to make a lot of things easier when we use them.

Two basic rules we need to know are these:

  • Items in a set are unique. We can not have a set that contains two items that are equal.
  • Items in a set are not ordered. Depending on the implementation, items may be sorted using the hash of the value stored, but when you use sets you need to assume items are ordered in a random manner.

And a cool guarantee they provide us: Checking if an element is present on a set has a time complexity constant (O(1)), always. This means, checking if a set contains an element is super fast.

The most popular implementation of a set used to achieve this is the hashed set. Oversimplified, it basically stores the items in a key-value store, where the key is a hash of the value stored.

So, to create a set in Python we use the constructor set which receives any iterable: my_pets = set([‘dog’, ‘cat’, ‘parrot’]) (no, I don’t have a parrot, nor a cat, dog person here).

Curly braces may be used too, which will avoid creating an intermediate list, but as they are also used for dictionaries, you can not create an empty set with curly braces. Also, someone can get confused, so I avoid them and stick to the constructor.

Sets are collections, therefore they are iterable:

my_pets = set(['dog', 'cat', 'parrot']) for pet in my_pets: print('Hello, <>!'.format(pet)) 

The above program serves as a demonstration of how elements in a set are ordered, below is the output of the program where you can see the order I defined was not respected by the interpreter:

Hello, dog! Hello, parrot! Hello, cat! 

So, with this information, let’s just dive into these cool operations.

Intersection

The intersection between two sets, results in a third set that contains the elements present in both.

For example, if I calculate the intersection between and , the output will be .

If this helps you understand, here is a naive implementation in Python:

a = set([1, 2, 3]) b = set([2, 3, 4]) result = print(result) 

Man, is Python awesome or what? Of course, this will print as expected. Anyway, that was irrelevant because Python provides a function to do this as part of its standard library. The same can be achieved with the following:

a = set([1, 2, 3]) b = set([2, 3, 4]) result = a.intersection(b) print(result) 

Notice that, because of the nature of the operation, a.intersection(b) and b.intersection(a) is the same. It is a commutative operation.

Union

The union between two sets, results in a third set with all the elements from both sets.

Читайте также:  Com server on python

For example, if I calculate the union between and , the output will be . Kind of like a concatenation, but having in mind that sets can not have repeated elements.

Again, let’s see a naive implementation in Python:

a = set([1, 2, 3]) b = set([2, 3, 4]) c = set() for element in a: c.add(element) for element in b: c.add(element) print(c) 

As expected, the output is . Again, though, Python does provide a native function to do this:

a = set([1, 2, 3]) b = set([2, 3, 4]) c = a.union(b) print(c) 

Notice that, because of the nature of the operation, a.union(b) and b.union(a) is the same. It is a commutative operation.

Difference

The difference between two sets results in a third set with the element from the first, that are not present on the second. Right now I’m going to tell you, this operation is not commutative.

For example, if I have a set a = and a set b = , the difference between a and b is and the difference between b and a is .

Here’s a naive implementation:

a = set([1, 2, 3]) b = set([2, 3, 4]) c = print(c) 

This outputs as expected, and will print if we invert a and b . Again, an implementation using Python’s standard lib:

a = set([1, 2, 3]) b = set([2, 3, 4]) c = a.difference(b) print(c) 

Symmetric difference

The symmetric difference between two sets results in a third set with the elements, from both sets, that are not present on the other.

For example, if I calculate the symmetric difference between and , the output will be . This operation is commutative.

Here’s a naive implementation:

a = set([1, 2, 3]) b = set([2, 3, 4]) c = set() for element in a: if element not in b: c.add(element) for element in b: if element not in a: c.add(element) print(c) 

The above implementation will print , as expected. Of course, Python has this on its standard libary too: symmetric_difference .

a = set([1, 2, 3]) b = set([2, 3, 4]) c = a.symmetric_difference(b) print(c) 

Conclusion

Sets are really useful, and actually pretty fun. Give them a try. I lived a lot of time constrained to lists, and when I finally sat down and learned how to work with sets started finding better, more elegant solutions to a lot of problems.

Источник

Python Set Operations: Union, Intersection, and Difference – With 10 Examples

In this tutorial, we look at set operations in Python and other operations performed on sets. Furthermore, we look at the different methods on sets as well as examples of set operations in Python. Check out this article for a deeper look into combinatorics with Python.

A set is a collection of unordered elements. Each element must be distinct and immutable. However, a set itself is mutable.

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

The concept of a set has been explicitly translated from mathematics into programming languages like Python. With it, some extremely helpful methods have come, such as union() , intersection() , and difference() , also directly translated from mathematics.

Sets are not simply a fundamental concept in mathematics. Throughout your programming career, you’ll likely come across a variety of challenges that may be solved significantly more quickly by using sets.

If you are a complete beginner to Python, we recommend you check out this track. If you are a beginner with some knowledge of Python, check out the course Python Basics Part 3, which covers the basics of variables, lists, conditional statements, loops, and functions.

Читайте также:  Check all checkbox html php

Sets and Set Operations in Python

A set is defined by enclosing all of the items (i.e., elements) in curly brackets and separating them with a comma or using the built-in set() method. It can include an unlimited number of elements of various categories (integer, float, tuple, string, etc.).

However, a set may not contain mutable items such as lists, sets, or dictionaries. Visit this article to learn more about the differences between lists, tuples, and sets. LearnPython.com is an incredible platform that helps you get started with Python.

Empty sets can be slightly tricky to use in Python. In Python, empty curly braces result in an empty dictionary; however, we cannot use them to initialize an empty set. Instead, we use the set() function without any arguments to create a set with no elements.

See the code below to understand these concepts:

# A set of integers int_set = # A set of mixed data types mixed_set = # All set elements are unique my_set = print(my_set) # Output: # A set can be made from a list my_set = set([1, 2, 3, 2, 4, 5, 5]) print(my_set) # Output:

Modifying a Set in Python

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

The add() method is used to add a single element, and the update() method is used to update multiple components. Tuples, lists, strings, and other sets may be passed to the update() method. Duplicates are avoided in all circumstances.

The following code illustrates these examples.

# Initialize a set my_set = # Add an element to the set # Output: my_set.add(21) print(my_set) # Add more than one element to the set # Output: my_set.update([20, 13, 8]) print(my_set)

Removing Elements From a Set

The methods discard() and remove() are used to delete a specific item from a set. They are identical with only one difference. The discard() method leaves the set unmodified If the element is not present in the set. The remove() method, on the other hand, throws an error if the element is not present in the set.

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

# Initialize a set my_set = print(my_set) # Discard an element my_set.discard(40) print(my_set) # Output: # Remove an element my_set.remove(60) # KeyError!

We may also use the pop() method to remove and return an item. However, there is no way to know which item will be popped because the set is an unordered data type. It’s absolutely random!

Note that the clear() method is used to delete all elements from a set.

# Initialize a set my_set = set("LearnPython") # Pop an element print(my_set.pop()) # Output: random element # Clear the set my_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 distinction between an operator and a method.

In Python, a method is similar to a function except it is tied to an object. When we call a method on an object, it may or may not affect that object – in this situation, a set. It’s worth noting that each operator corresponds to a distinct Python special function. So, they both accomplish the same thing but have distinct syntax requirements.

Читайте также:  Lego mindstorms with java

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

Python Union Operation With Example

The union of two sets is the set of all the elements, without duplicates, contained in either or both of the sets. In Python, you may use either the union() method or the | syntax to find the union. Let’s look at a Python union example.

# Defining the two sets first_set = second_set = # Creating the union of the two sets new_set = first_set | second_set print(new_set) # Output:

Running the code above creates two sets: first_set and second_set . Then, the union operator creates a new_set with all unique elements from the first_set and the second_set .

The same is achieved using the union() 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) results in the same set as second_set.union(first_set) .

Python Intersection Operation With Example

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

# Defining the two sets first_set = second_set = # Creating the intersection of the two sets new_set = first_set & second_set print(new_set) # Output:

Running the code above creates two sets: first_set and second_set . Then, the intersection operator creates a new_set with all unique elements from the first_set and the second_set .

The same is achieved using the intersection() method:

new_set = first_set.intersection(second_set)

Since the intersection method produces a set of elements that are common to both sets, it is symmetric. So, first_set.intersection(second_set) results in the same set as second_set.intersection(first_set) .

Python Set Difference Operation With Example

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

# Defining the two sets first_set = second_set = # Creating the difference of the two sets new_set = first_set — second_set print(new_set) # Output:

You may also use the difference() method:

# Difference of two sets # Initialize A and B first_set = second_set = # Creating the difference between the two sets new_set = second_set.difference(first_set) print(new_set) # Output:

As shown in the example, the difference operator is not symmetric. Which set you name first matters and influences the result of the new_set .

Make Use of Python Set Operations

In this tutorial, you have learned how to define set operations in Python. In addition, we have become familiar with the functions, operators, and methods used to work with sets. If you want to learn more about Python sets, e.g., how to get the symmetric difference, visit the article “Python Set Operations and More: All You Need to Know About Python Sets.”

Источник

Оцените статью