Union two sets python

How to join two or more sets in Python

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Overview

Sets can be joined in Python in a number of different ways. For instance, update() adds all the elements of one set to the other. Similarly, union() combines all the elements of the two sets and returns them in a new set. Both union() and update() operations exclude duplicate elements.

Example for union()

set1 =
set2 =
set_union = set1.union(set2)
print(set_union)

Explanation

Lines 1–5: The union operation returns a new set, set_union , containing all the items from the previous 2 sets, set1 , set2 .

Example for update()

set1 =
set2 =
set1.update(set2)
print(set1)

Explanation

Lines 1–5: The update method adds the values of set2 into set1 .

The intersection_update() and intersection() methods

There are also some methods that keep only duplicates. These are intersection_update() and intersection() .

The intersection_update() method only stores the items that are present in both sets. While the intersection() method returns a new set containing items that are present in both sets.

Example for intersection_update()

set1 =
set2 =
set1.intersection_update(set2)
print(set1)

Explanation

Lines 1–6: The intersection_update() only keeps those items in set1 that are present in both sets.

Example for intersection()

set1 =
set2 =
set3 = set1.intersection(set2)
print(set3)

Explanation

Lines 1–6: The intersection() method returns a new set, set3 , that contains values that are present in both the previous sets.

The symmetric_difference_update() and symmetric_difference() method

Another way of joining sets is by keeping all the elements except duplicates. For this operation we use symmetric_difference_update() and symmetric_difference() method.

The symmetric_difference_update() method stores only the elements that are not present in both sets. While symmetric_difference() stores only the elements that are not present in both sets in the new set and returns it.

Источник

Python Set Union

Summary: in this tutorial, you’ll learn how to union two or more sets by using the Python set union() or set union operator (|).

Introduction to the set union

The union of two sets returns a new set that contains distinct elements from both sets.

Suppose that you have the following sets:

s1 = 'Python', 'Java'> s2 = 'C#', 'Java'>Code language: JavaScript (javascript)

The union of the s1 and s2 sets returns the following set:

'Java','Python', 'C#'>Code language: JavaScript (javascript)

Typically, you use the Venn diagram to illustrate the union of two sets. For example:

Python Set Union Example

Union sets using union() method

In Python, to union two or more sets, you use the union() method:

new_set = set.union(another_set, . )Code language: JavaScript (javascript)

The following example shows how to union the s1 and s2 sets:

s1 = 'Python', 'Java'> s2 = 'C#', 'Java'> s = s1.union(s2) print(s)Code language: PHP (php)
'Python', 'Java', 'C#'> Code language: JavaScript (javascript)

Union sets using the | operator

Python provides you with the set union operator | that allows you to union two sets:

The set union operator ( | ) returns a new set that consists of distinct elements from both set1 and set2 .

The following example shows how to use the union operator ( | ) to union the s1 and s2 sets:

s1 = 'Python', 'Java'> s2 = 'C#', 'Java'> s = s1 | s2 print(s)Code language: PHP (php)
'Java', 'C#', 'Python'> Code language: JavaScript (javascript)

The union() method vs. set union operator

In fact, the union() method accepts one or more iterables, converts the iterables to sets, and performs the union.

The following example shows how to pass a list to the union() method:

rates = 1, 2, 3> ranks = [2, 3, 4] ratings = rates.union(ranks) print(ratings)Code language: PHP (php)

However, the union operator ( | ) only allows sets, not iterables like the union() method.

The following example causes an error:

rates = ranks = [2, 3, 4] ratings = rates | ranks
TypeError: unsupported operand type(s) for |: 'set' and 'list'Code language: JavaScript (javascript)

In conclusion, the union() method accepts the iterables while the union operator only allows sets.

Summary

  • The union of two or more sets returns distinct values from both sets.
  • Use union() method or set union operator ( | ) to union two or more sets.
  • The union() method accepts one or more iterables while the set union operator ( | ) only accepts sets.

Источник

Python Set union() — A Complete Guide in 5 Minutes

Python Set union() - A Complete Guide in 5 Minutes

Python programmers have several methods for combining two sets into one. In this blog post, we’ll explore the set union() method, and we’ll look at some examples of how to use it. We’ll also discuss some of the benefits of using set union() , and we’ll see why it’s a popular tool for Python developers.

Finally, we’ll go over some advanced use cases and examine the efficiency of set union() . So let’s get started!

Don’t feel like reading? Watch my video instead:

Python Set Union — The Basics

In this section, we’ll go over the basic definition and usage of the set union() function in Python, explore its syntax and return value.

Definition and Usage of Set Union in Python

Before we get into some examples, let’s start with the basics. What is a set union() ? As you might expect, it’s a function that combines two sets into one. The function can combine one set with multiple other sets or Python iterable objects.

For example, take a look at the following two sets — A and B:

Image 1 - Python set union - two sets (image by author)

Calculating a union between these sets means we want to create a new set that has all distinct elements from both:

Image 2 - Python set union - the union between two sets (image by author)

Python set union() is oftentimes represented with a Venn diagram. Here’s what it would look like:

Image 3 - Python set union as a Venn diagram (image by author)

The set on the left has elements R and Julia that aren’t present in the set on the right. Likewise, the set on the right has JavaScript and Go as distinct elements. There’s one element common to both sets — Python.

Keep in mind: If an item is present in more than one set, the resulting set will list the item only once.

Syntax of Set Union in Python

# Combine two sets set1.union(set2)  # Combine multiple sets set1.union(set2, set3, . ) 
  • set1 — The iterable to unify with.
  • set2 , set3 — Optional set(s), other iterables to unify with.

Return value of Set Union in Python

The set union() function in Python returns a new set which is the union of all sets with the first one — but only if set(s) or iterable object(s) were passed to the union() function.

If no arguments were passed into the union() function, a copy of the set is returned.

Python Set Union Function Example

We’ll declare two sets, just as on the above images:

  • A — Contains programming languages used in data science
  • B — Contains programming languages used in web development

Some programming languages are interchangeable, like Python, so it’s present in both sets. It should only get printed once, as we’ve seen before:

A = 'Python', 'R', 'Julia'> B = 'Python', 'JavaScript', 'Go'>  print(f"A U B = A.union(B)>") 

If you don’t specify any parameters to the Python set union() function, the set gets copied:

You can verify it was copied by printing its memory address:

A = 'Python', 'R', 'Julia'> A_copy = A.union()  print(hex(id(A))) print(hex(id(A_copy))) 

You won’t see the identical values, and that’s not the point. The important thing is that they’re different, indicating the set was copied to a different memory address.

Let’s now explore a shorter way to get the union of multiple sets.

Python Set Union Using the | Operator

There’s no need to call the Python set union() function every time. You can use the pipe ( | ) operator instead:

A = 'Python', 'R', 'Julia'> B = 'Python', 'JavaScript', 'Go'>  print(f"A U B = A | B>") 

Everything else remains the same. This approach is more compact and readable than the first one, at least if you’re combining two sets.

Python Set Union Advanced Examples

We’ll now go over a couple of “advanced” union examples and use cases:

  • Multiple set arguments
  • Set update vs. set union
  • Python union on iterable objects

Multiple Set Arguments

You can get the union of one set with multiple sets. We’ll declare yet another set containing programming languages used in scientific computing and calculate the union of all three.

The calculation works both by using the regular syntax and the shorthand pipe syntax:

A = 'Python', 'R', 'Julia'> B = 'Python', 'JavaScript', 'Go'> C = 'R', 'Matlab', 'Octave'>  print(f"A U B U C = A.union(B, C)>") print(f"A U B U C = A | B | C>") 

Set Update vs. Union

You can perform the union operation in Python both with set.update() and set.union() . The first one adds all missing elements to the set on which it is called and returns None , while the latter creates and returns a new set.

Here’s how set.update() works:

A = 'Python', 'R', 'Julia'> B = 'Python', 'JavaScript', 'Go'>  A.update(B) print(A) 

As you can see, the update happens in place. You can’t save the results of the update operation to a new set, so keep that in mind:

A = 'Python', 'R', 'Julia'> B = 'Python', 'JavaScript', 'Go'>  C = A.update(B) print(C) 

Python Union on Iterable Objects

You can call the union() function on a Python set and provide any iterable object as an argument — here’s an example for a Python list:

l1 = 1, 2, 3> l2 = [2, 3, 4]  print(l1.union(l2)) 

Keep in mind: You can’t use the shorthand pipe operator:

l1 = 1, 2, 3> l2 = [2, 3, 4]  print(l1 | l2) 

Image 4 - TypeError when trying to union Python set and list (image by author)

You also can’t use anything but a Python set first — as no other data type has the union() function:

l1 = [1, 2, 3] l2 = [2, 3, 4]  print(l1.union(l2)) 

Image 5 - AttributeError when trying to call union() on a Python list (image by author)

Long story short — You always have to use the union() function instead of the pipe operator and you must call the function on a set.

Python Set Union Performance (Time Complexity)

We’ll now analyze the time complexity of the set union operation in Python. I’ve found the source code over at Finxter blog and slightly modified it. To summarize:

  • Time complexity on a set with n elements and set arguments with m elements is O(n + m).
  • Inserting an element into a set has a complexity of O(1).

Here’s the Python code that calculates and displays a figure of set size on the X-axis and runtime in seconds on the Y-axis. I’ve run the code on M1 Pro MacBook Pro 16":

import time import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (12, 5) plt.rcParams['axes.spines.top'] = False plt.rcParams['axes.spines.right'] = False  # Calculations sizes = [i * 10**5 for i in range(100)] runtimes = []  for size in sizes:  s = set(range(size))  t = set(range(0, size, 2))   t1 = time.time()  s.union(t)  t2 = time.time()   runtimes.append(t2 - t1)  # Plot plt.figure() plt.plot(sizes, runtimes, lw=3, color='#101010') plt.title('Python set union() runtime vs. set size', size=20) plt.xlabel('Set size', size=14) plt.ylabel('Runtime (s)', size=14); 

Image 6 - Python set union() time complexity chart (image by author)

Conclusion

Python set union is simple to understand. We went through the definition and intuition, and slowly built our way towards understanding more complicated use cases. You have to admit — even the advanced section was easy to digest.

I hope that this article has helped you develop a better understanding of the Python set union function. As always, if you have any questions or comments, please feel free to ask in the comment section below. Happy coding!

Learn More

Stay connected

Источник

Читайте также:  Docker install php pdo mysql
Оцените статью