Sets in Python – Real Python (2023)

• Defining a Set
• Set Size and Membership
• Operating on a Set
• Operators vs. Methods
• Available Operators and Methods
• Modifying a Set
• Augmented Assignment Operators and Methods
• Other Methods For Modifying Sets
• Frozen Sets
• Conclusion

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Sets in Python

Perhaps you recall learning about sets and set theory at some point in your mathematical education. Maybe you even remember Venn diagrams:

If this doesn’t ring a bell, don’t worry! This tutorial should still be easily accessible for you.

In mathematics, a rigorous definition of a set can be abstract and difficult to grasp. Practically though, a set can be thought of simply as a well-defined collection of distinct objects, typically called elements or members.

Grouping objects into a set can be useful in programming as well, and Python provides a built-in set type to do so. Sets are distinguished from other object types by the unique operations that can be performed on them.

Here’s what you’ll learn in this tutorial: You’ll see how to define set objects in Python and discover the operations that they support. As with the earlier tutorials on lists and dictionaries, when you are finished with this tutorial, you should have a good feel for when a set is an appropriate choice. You will also learn about frozen sets, which are similar to sets except for one important detail.

Take the Quiz: Test your knowledge with our interactive “Python Sets” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

Defining a Set

Python’s built-in `set` type has the following characteristics:

• Sets are unordered.
• Set elements are unique. Duplicate elements are not allowed.
• A set itself may be modified, but the elements contained in the set must be of an immutable type.

Let’s see what all that means, and how you can work with sets in Python.

A set can be created in two ways. First, you can define a set with the built-in `set()` function:

``x = set(<iter>)``

In this case, the argument `<iter>` is an iterable—again, for the moment, think list or tuple—that generates the list of objects to be included in the set. This is analogous to the `<iter>` argument given to the `.extend()` list method:

>>>

``>>> x = set(['foo', 'bar', 'baz', 'foo', 'qux'])>>> x{'qux', 'foo', 'bar', 'baz'}>>> x = set(('foo', 'bar', 'baz', 'foo', 'qux'))>>> x{'qux', 'foo', 'bar', 'baz'}``

Strings are also iterable, so a string can be passed to `set()` as well. You have already seen that `list(s)` generates a list of the characters in the string `s`. Similarly, `set(s)` generates a set of the characters in `s`:

>>>

``>>> s = 'quux'>>> list(s)['q', 'u', 'u', 'x']>>> set(s){'x', 'u', 'q'}``

You can see that the resulting sets are unordered: the original order, as specified in the definition, is not necessarily preserved. Additionally, duplicate values are only represented in the set once, as with the string `'foo'` in the first two examples and the letter `'u'` in the third.

Alternately, a set can be defined with curly braces (`{}`):

``x = {<obj>, <obj>, ..., <obj>}``

When a set is defined this way, each `<obj>` becomes a distinct element of the set, even if it is an iterable. This behavior is similar to that of the `.append()` list method.

Thus, the sets shown above can also be defined like this:

>>>

``>>> x = {'foo', 'bar', 'baz', 'foo', 'qux'}>>> x{'qux', 'foo', 'bar', 'baz'}>>> x = {'q', 'u', 'u', 'x'}>>> x{'x', 'q', 'u'}``

To recap:

• The argument to `set()` is an iterable. It generates a list of elements to be placed into the set.
• The objects in curly braces are placed into the set intact, even if they are iterable.

Observe the difference between these two set definitions:

>>>

``>>> {'foo'}{'foo'}>>> set('foo'){'o', 'f'}``

A set can be empty. However, recall that Python interprets empty curly braces (`{}`) as an empty dictionary, so the only way to define an empty set is with the `set()` function:

>>>

``>>> x = set()>>> type(x)<class 'set'>>>> xset()>>> x = {}>>> type(x)<class 'dict'>``

An empty set is falsy in a Boolean context:

>>>

``>>> x = set()>>> bool(x)False>>> x or 11>>> x and 1set()``

You might think the most intuitive sets would contain similar objects—for example, even numbers or surnames:

>>>

``>>> s1 = {2, 4, 6, 8, 10}>>> s2 = {'Smith', 'McArthur', 'Wilson', 'Johansson'}``

Python does not require this, though. The elements in a set can be objects of different types:

>>>

``>>> x = {42, 'foo', 3.14159, None}>>> x{None, 'foo', 42, 3.14159}``

Don’t forget that set elements must be immutable. For example, a tuple may be included in a set:

>>>

``>>> x = {42, 'foo', (1, 2, 3), 3.14159}>>> x{42, 'foo', 3.14159, (1, 2, 3)}``

But lists and dictionaries are mutable, so they can’t be set elements:

>>>

``>>> a = [1, 2, 3]>>> {a}Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> {a}TypeError: unhashable type: 'list'>>> d = {'a': 1, 'b': 2}>>> {d}Traceback (most recent call last): File "<pyshell#72>", line 1, in <module> {d}TypeError: unhashable type: 'dict'``

(Video) Python Data Structures: Sets, Frozensets, and Multisets (Bags)

Set Size and Membership

The `len()` function returns the number of elements in a set, and the in and not in operators can be used to test for membership:

>>>

``>>> x = {'foo', 'bar', 'baz'}>>> len(x)3>>> 'bar' in xTrue>>> 'qux' in xFalse``

Operating on a Set

Many of the operations that can be used for Python’s other composite data types don’t make sense for sets. For example, sets can’t be indexed or sliced. However, Python provides a whole host of operations on set objects that generally mimic the operations that are defined for mathematical sets.

Operators vs. Methods

Most, though not quite all, set operations in Python can be performed in two different ways: by operator or by method. Let’s take a look at how these operators and methods work, using set union as an example.

Given two sets, `x1` and `x2`, the union of `x1` and `x2` is a set consisting of all elements in either set.

Consider these two sets:

``x1 = {'foo', 'bar', 'baz'}x2 = {'baz', 'qux', 'quux'}``

The union of `x1` and `x2` is `{'foo', 'bar', 'baz', 'qux', 'quux'}`.

Note: Notice that the element `'baz'`, which appears in both `x1` and `x2`, appears only once in the union. Sets never contain duplicate values.

In Python, set union can be performed with the `|` operator:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'baz', 'qux', 'quux'}>>> x1 | x2{'baz', 'quux', 'qux', 'bar', 'foo'}``

Set union can also be obtained with the `.union()` method. The method is invoked on one of the sets, and the other is passed as an argument:

>>>

``>>> x1.union(x2){'baz', 'quux', 'qux', 'bar', 'foo'}``

The way they are used in the examples above, the operator and method behave identically. But there is a subtle difference between them. When you use the `|` operator, both operands must be sets. The `.union()` method, on the other hand, will take any iterable as an argument, convert it to a set, and then perform the union.

Observe the difference between these two statements:

>>>

``>>> x1 | ('baz', 'qux', 'quux')Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> x1 | ('baz', 'qux', 'quux')TypeError: unsupported operand type(s) for |: 'set' and 'tuple'>>> x1.union(('baz', 'qux', 'quux')){'baz', 'quux', 'qux', 'bar', 'foo'}``

Both attempt to compute the union of `x1` and the tuple `('baz', 'qux', 'quux')`. This fails with the `|` operator but succeeds with the `.union()` method.

Available Operators and Methods

Below is a list of the set operations available in Python. Some are performed by operator, some by method, and some by both. The principle outlined above generally applies: where a set is expected, methods will typically accept any iterable as an argument, but operators require actual sets as operands.

`x1.union(x2[, x3 ...])`

`x1 | x2 [| x3 ...]`

Compute the union of two or more sets.

`x1.union(x2)` and `x1 | x2` both return the set of all elements in either `x1` or `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'baz', 'qux', 'quux'}>>> x1.union(x2){'foo', 'qux', 'quux', 'baz', 'bar'}>>> x1 | x2{'foo', 'qux', 'quux', 'baz', 'bar'}``

More than two sets may be specified with either the operator or the method:

>>>

``>>> a = {1, 2, 3, 4}>>> b = {2, 3, 4, 5}>>> c = {3, 4, 5, 6}>>> d = {4, 5, 6, 7}>>> a.union(b, c, d){1, 2, 3, 4, 5, 6, 7}>>> a | b | c | d{1, 2, 3, 4, 5, 6, 7}``

The resulting set contains all elements that are present in any of the specified sets.

`x1.intersection(x2[, x3 ...])`

`x1 & x2 [& x3 ...]`

Compute the intersection of two or more sets.

`x1.intersection(x2)` and `x1 & x2` return the set of elements common to both `x1` and `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'baz', 'qux', 'quux'}>>> x1.intersection(x2){'baz'}>>> x1 & x2{'baz'}``

You can specify multiple sets with the intersection method and operator, just like you can with set union:

>>>

``>>> a = {1, 2, 3, 4}>>> b = {2, 3, 4, 5}>>> c = {3, 4, 5, 6}>>> d = {4, 5, 6, 7}>>> a.intersection(b, c, d){4}>>> a & b & c & d{4}``

The resulting set contains only elements that are present in all of the specified sets.

`x1.difference(x2[, x3 ...])`

`x1 - x2 [- x3 ...]`

Compute the difference between two or more sets.

`x1.difference(x2)` and `x1 - x2` return the set of all elements that are in `x1` but not in `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'baz', 'qux', 'quux'}>>> x1.difference(x2){'foo', 'bar'}>>> x1 - x2{'foo', 'bar'}``

Another way to think of this is that `x1.difference(x2)` and `x1 - x2` return the set that results when any elements in `x2` are removed or subtracted from `x1`.

Once again, you can specify more than two sets:

>>>

(Video) Defining a Set in Python

``>>> a = {1, 2, 3, 30, 300}>>> b = {10, 20, 30, 40}>>> c = {100, 200, 300, 400}>>> a.difference(b, c){1, 2, 3}>>> a - b - c{1, 2, 3}``

When multiple sets are specified, the operation is performed from left to right. In the example above, `a - b` is computed first, resulting in `{1, 2, 3, 300}`. Then `c` is subtracted from that set, leaving `{1, 2, 3}`:

`x1.symmetric_difference(x2)`

`x1 ^ x2 [^ x3 ...]`

Compute the symmetric difference between sets.

`x1.symmetric_difference(x2)` and `x1 ^ x2` return the set of all elements in either `x1` or `x2`, but not both:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'baz', 'qux', 'quux'}>>> x1.symmetric_difference(x2){'foo', 'qux', 'quux', 'bar'}>>> x1 ^ x2{'foo', 'qux', 'quux', 'bar'}``

The `^` operator also allows more than two sets:

>>>

``>>> a = {1, 2, 3, 4, 5}>>> b = {10, 2, 3, 4, 50}>>> c = {1, 50, 100}>>> a ^ b ^ c{100, 5, 10}``

As with the difference operator, when multiple sets are specified, the operation is performed from left to right.

Curiously, although the `^` operator allows multiple sets, the `.symmetric_difference()` method doesn’t:

>>>

``>>> a = {1, 2, 3, 4, 5}>>> b = {10, 2, 3, 4, 50}>>> c = {1, 50, 100}>>> a.symmetric_difference(b, c)Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> a.symmetric_difference(b, c)TypeError: symmetric_difference() takes exactly one argument (2 given)``

`x1.isdisjoint(x2)`

Determines whether or not two sets have any elements in common.

`x1.isdisjoint(x2)` returns `True` if `x1` and `x2` have no elements in common:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'baz', 'qux', 'quux'}>>> x1.isdisjoint(x2)False>>> x2 - {'baz'}{'quux', 'qux'}>>> x1.isdisjoint(x2 - {'baz'})True``

If `x1.isdisjoint(x2)` is `True`, then `x1 & x2` is the empty set:

>>>

``>>> x1 = {1, 3, 5}>>> x2 = {2, 4, 6}>>> x1.isdisjoint(x2)True>>> x1 & x2set()``

Note: There is no operator that corresponds to the `.isdisjoint()` method.

`x1.issubset(x2)`

`x1 <= x2`

Determine whether one set is a subset of the other.

In set theory, a set `x1` is considered a subset of another set `x2` if every element of `x1` is in `x2`.

`x1.issubset(x2)` and `x1 <= x2` return `True` if `x1` is a subset of `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x1.issubset({'foo', 'bar', 'baz', 'qux', 'quux'})True>>> x2 = {'baz', 'qux', 'quux'}>>> x1 <= x2False``

A set is considered to be a subset of itself:

>>>

``>>> x = {1, 2, 3, 4, 5}>>> x.issubset(x)True>>> x <= xTrue``

It seems strange, perhaps. But it fits the definition—every element of `x` is in `x`.

`x1 < x2`

Determines whether one set is a proper subset of the other.

A proper subset is the same as a subset, except that the sets can’t be identical. A set `x1` is considered a proper subset of another set `x2` if every element of `x1` is in `x2`, and `x1` and `x2` are not equal.

`x1 < x2` returns `True` if `x1` is a proper subset of `x2`:

>>>

``>>> x1 = {'foo', 'bar'}>>> x2 = {'foo', 'bar', 'baz'}>>> x1 < x2True>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'foo', 'bar', 'baz'}>>> x1 < x2False``

While a set is considered a subset of itself, it is not a proper subset of itself:

>>>

``>>> x = {1, 2, 3, 4, 5}>>> x <= xTrue>>> x < xFalse``

Note: The `<` operator is the only way to test whether a set is a proper subset. There is no corresponding method.

`x1.issuperset(x2)`

`x1 >= x2`

Determine whether one set is a superset of the other.

A superset is the reverse of a subset. A set `x1` is considered a superset of another set `x2` if `x1` contains every element of `x2`.

`x1.issuperset(x2)` and `x1 >= x2` return `True` if `x1` is a superset of `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x1.issuperset({'foo', 'bar'})True>>> x2 = {'baz', 'qux', 'quux'}>>> x1 >= x2False``

You have already seen that a set is considered a subset of itself. A set is also considered a superset of itself:

>>>

``>>> x = {1, 2, 3, 4, 5}>>> x.issuperset(x)True>>> x >= xTrue``

`x1 > x2`

(Video) Simulating Real-Life Processes in Python

Determines whether one set is a proper superset of the other.

A proper superset is the same as a superset, except that the sets can’t be identical. A set `x1` is considered a proper superset of another set `x2` if `x1` contains every element of `x2`, and `x1` and `x2` are not equal.

`x1 > x2` returns `True` if `x1` is a proper superset of `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'foo', 'bar'}>>> x1 > x2True>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'foo', 'bar', 'baz'}>>> x1 > x2False``

A set is not a proper superset of itself:

>>>

``>>> x = {1, 2, 3, 4, 5}>>> x > xFalse``

Note: The `>` operator is the only way to test whether a set is a proper superset. There is no corresponding method.

Modifying a Set

Although the elements contained in a set must be of immutable type, sets themselves can be modified. Like the operations above, there are a mix of operators and methods that can be used to change the contents of a set.

Augmented Assignment Operators and Methods

Each of the union, intersection, difference, and symmetric difference operators listed above has an augmented assignment form that can be used to modify a set. For each, there is a corresponding method as well.

`x1.update(x2[, x3 ...])`

`x1 |= x2 [| x3 ...]`

Modify a set by union.

`x1.update(x2)` and `x1 |= x2` add to `x1` any elements in `x2` that `x1` does not already have:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'foo', 'baz', 'qux'}>>> x1 |= x2>>> x1{'qux', 'foo', 'bar', 'baz'}>>> x1.update(['corge', 'garply'])>>> x1{'qux', 'corge', 'garply', 'foo', 'bar', 'baz'}``

`x1.intersection_update(x2[, x3 ...])`

`x1 &= x2 [& x3 ...]`

Modify a set by intersection.

`x1.intersection_update(x2)` and `x1 &= x2` update `x1`, retaining only elements found in both `x1` and `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'foo', 'baz', 'qux'}>>> x1 &= x2>>> x1{'foo', 'baz'}>>> x1.intersection_update(['baz', 'qux'])>>> x1{'baz'}``

`x1.difference_update(x2[, x3 ...])`

`x1 -= x2 [| x3 ...]`

Modify a set by difference.

`x1.difference_update(x2)` and `x1 -= x2` update `x1`, removing elements found in `x2`:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'foo', 'baz', 'qux'}>>> x1 -= x2>>> x1{'bar'}>>> x1.difference_update(['foo', 'bar', 'qux'])>>> x1set()``

`x1.symmetric_difference_update(x2)`

`x1 ^= x2`

Modify a set by symmetric difference.

`x1.symmetric_difference_update(x2)` and `x1 ^= x2` update `x1`, retaining elements found in either `x1` or `x2`, but not both:

>>>

``>>> x1 = {'foo', 'bar', 'baz'}>>> x2 = {'foo', 'baz', 'qux'}>>> >>> x1 ^= x2>>> x1{'bar', 'qux'}>>> >>> x1.symmetric_difference_update(['qux', 'corge'])>>> x1{'bar', 'corge'}``

Other Methods For Modifying Sets

Aside from the augmented operators above, Python supports several additional methods that modify sets.

`x.add(<elem>)`

Adds an element to a set.

`x.add(<elem>)` adds `<elem>`, which must be a single immutable object, to `x`:

>>>

``>>> x = {'foo', 'bar', 'baz'}>>> x.add('qux')>>> x{'bar', 'baz', 'foo', 'qux'}``

`x.remove(<elem>)`

Removes an element from a set.

`x.remove(<elem>)` removes `<elem>` from `x`. Python raises an exception if `<elem>` is not in `x`:

>>>

``>>> x = {'foo', 'bar', 'baz'}>>> x.remove('baz')>>> x{'bar', 'foo'}>>> x.remove('qux')Traceback (most recent call last): File "<pyshell#58>", line 1, in <module> x.remove('qux')KeyError: 'qux'``

`x.discard(<elem>)`

Removes an element from a set.

`x.discard(<elem>)` also removes `<elem>` from `x`. However, if `<elem>` is not in `x`, this method quietly does nothing instead of raising an exception:

>>>

(Video) Start Using a Build System & Continuous Integration in Python | Real Python Podcast #137

``>>> x = {'foo', 'bar', 'baz'}>>> x.discard('baz')>>> x{'bar', 'foo'}>>> x.discard('qux')>>> x{'bar', 'foo'}``

`x.pop()`

Removes a random element from a set.

`x.pop()` removes and returns an arbitrarily chosen element from `x`. If `x` is empty, `x.pop()` raises an exception:

>>>

``>>> x = {'foo', 'bar', 'baz'}>>> x.pop()'bar'>>> x{'baz', 'foo'}>>> x.pop()'baz'>>> x{'foo'}>>> x.pop()'foo'>>> xset()>>> x.pop()Traceback (most recent call last): File "<pyshell#82>", line 1, in <module> x.pop()KeyError: 'pop from an empty set'``

`x.clear()`

Clears a set.

`x.clear()` removes all elements from `x`:

>>>

``>>> x = {'foo', 'bar', 'baz'}>>> x{'foo', 'bar', 'baz'}>>> >>> x.clear()>>> xset()``

Frozen Sets

Python provides another built-in type called a frozenset, which is in all respects exactly like a set, except that a frozenset is immutable. You can perform non-modifying operations on a frozenset:

>>>

``>>> x = frozenset(['foo', 'bar', 'baz'])>>> xfrozenset({'foo', 'baz', 'bar'})>>> len(x)3>>> x & {'baz', 'qux', 'quux'}frozenset({'baz'})``

But methods that attempt to modify a frozenset fail:

>>>

``>>> x = frozenset(['foo', 'bar', 'baz'])>>> x.add('qux')Traceback (most recent call last): File "<pyshell#127>", line 1, in <module> x.add('qux')AttributeError: 'frozenset' object has no attribute 'add'>>> x.pop()Traceback (most recent call last): File "<pyshell#129>", line 1, in <module> x.pop()AttributeError: 'frozenset' object has no attribute 'pop'>>> x.clear()Traceback (most recent call last): File "<pyshell#131>", line 1, in <module> x.clear()AttributeError: 'frozenset' object has no attribute 'clear'>>> xfrozenset({'foo', 'bar', 'baz'})``

Deep Dive: Frozensets and Augmented Assignment

Since a frozenset is immutable, you might think it can’t be the target of an augmented assignment operator. But observe:

>>>

``>>> f = frozenset(['foo', 'bar', 'baz'])>>> s = {'baz', 'qux', 'quux'}>>> f &= s>>> ffrozenset({'baz'})``

What gives?

Python does not perform augmented assignments on frozensets in place. The statement `x &= s` is effectively equivalent to `x = x & s`. It isn’t modifying the original `x`. It is reassigning `x` to a new object, and the object `x` originally referenced is gone.

You can verify this with the `id()` function:

>>>

``>>> f = frozenset(['foo', 'bar', 'baz'])>>> id(f)56992872>>> s = {'baz', 'qux', 'quux'}>>> f &= s>>> ffrozenset({'baz'})>>> id(f)56992152``

`f` has a different integer identifier following the augmented assignment. It has been reassigned, not modified in place.

Some objects in Python are modified in place when they are the target of an augmented assignment operator. But frozensets aren’t.

Frozensets are useful in situations where you want to use a set, but you need an immutable object. For example, you can’t define a set whose elements are also sets, because set elements must be immutable:

>>>

``>>> x1 = set(['foo'])>>> x2 = set(['bar'])>>> x3 = set(['baz'])>>> x = {x1, x2, x3}Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> x = {x1, x2, x3}TypeError: unhashable type: 'set'``

If you really feel compelled to define a set of sets (hey, it could happen), you can do it if the elements are frozensets, because they are immutable:

>>>

``>>> x1 = frozenset(['foo'])>>> x2 = frozenset(['bar'])>>> x3 = frozenset(['baz'])>>> x = {x1, x2, x3}>>> x{frozenset({'bar'}), frozenset({'baz'}), frozenset({'foo'})}``

Likewise, recall from the previous tutorial on dictionaries that a dictionary key must be immutable. You can’t use the built-in set type as a dictionary key:

>>>

``>>> x = {1, 2, 3}>>> y = {'a', 'b', 'c'}>>> >>> d = {x: 'foo', y: 'bar'}Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> d = {x: 'foo', y: 'bar'}TypeError: unhashable type: 'set'``

If you find yourself needing to use sets as dictionary keys, you can use frozensets:

>>>

``>>> x = frozenset({1, 2, 3})>>> y = frozenset({'a', 'b', 'c'})>>> >>> d = {x: 'foo', y: 'bar'}>>> d{frozenset({1, 2, 3}): 'foo', frozenset({'c', 'a', 'b'}): 'bar'}``

Conclusion

In this tutorial, you learned how to define set objects in Python, and you became familiar with the functions, operators, and methods that can be used to work with sets.

You should now be comfortable with the basic built-in data types that Python provides.

Next, you will begin to explore how the code that operates on those objects is organized and structured in a Python program.

Take the Quiz: Test your knowledge with our interactive “Python Sets” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

«Dictionaries in Python

Sets in Python

Python Program Lexical Structure»

(Video) Introduction to Python Dictionaries: Python Basics

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Sets in Python

FAQs

Do sets exist in Python? ›

Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which is unordered, unchangeable*, and unindexed.

Which is used to create set in Python * [] {} set () ()? ›

To create a set, you use the set() function. The set() function takes any number of arguments, which are all items that will be added to the set. In Python, the set() constructor creates a new set object.

How does set () work in Python? ›

set() method is used to convert any of the iterable to sequence of iterable elements with distinct elements, commonly called Set.
1. Syntax : set(iterable)
2. Parameters : Any iterable sequence like list, tuple or dictionary.
3. Returns : An empty set if no element is passed.
Feb 19, 2022

Which of the following is true regarding set in Python? ›

Explanation: In python, elements of a set must not be mutable and sets are mutable. Thus, subsets can't exist.

Are sets faster in Python? ›

But in the case of searching for an element in a collection, sets are faster because sets have been implemented using hash tables. So basically Python does not have to search the full set, which means that the time complexity in average is O(1).

Does set exist? ›

Sets are objects in the universe of [pure] set theory. Informally, sets are formalization of the idea of a collection of mathematical objects. As for the existence, existence [of a set] in the pure mathematical sense means that in a mathematical universe there is a set with particular properties.

How are sets written in Python? ›

In Python, we create sets by placing all the elements inside curly braces {} , separated by comma. A set can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

Can sets have duplicates? ›

Sets cannot contain duplicates. Duplicates are discarded when initializing a set. If adding an element to a set, and that element is already contained in the set, then the set will not change.

How do you initialize a set in Python? ›

You can initialize a set by placing elements in between curly braces. Like other sequences, one set can have elements of multiple data-types. Moreover, you can also create a set from a list by using set() function.

Why use sets in Python? ›

A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.

What is the function of set? ›

A set function generally aims to measure subsets in some way. Measures are typical examples of "measuring" set functions. Therefore, the term "set function" is often used for avoiding confusion between the mathematical meaning of "measure" and its common language meaning.

What does set do in coding? ›

A set is a data structure that can store any number of unique values in any order you so wish. Set's are different from arrays in the sense that they only allow non-repeated, unique values within them.

Which of these a set is not true? ›

33. Which of these about a set is not true? a) Mutable data type b) Allows duplicate values c) Data type with unordered values d) Immutable data type Answer: d Explanation: A set is a mutable data type with non-duplicate, unordered values, providing the usual mathematical set operations.

Which one is true about the sets? ›

The correct answer of this question is Option D

Set is a collection of objects or elements which may or may not be well defined. The elements or objects collectively forming a set may or may not be mathematical. It can be in the form of numbers, functions etc. The elements may or may not be distinguishable.

Which of the following defines a set in Python? ›

A set is an unordered and mutable collection of unique elements. Sets are written with curly brackets ({}), being the elements separated by commas. The following code block shows two sets, containing a collection of numbers and cities. Any immutable data type can be an element of a set (e.g. strings and integers).

How efficient is set in Python? ›

Because sets cannot have multiple occurrences of the same element, it makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.

Why are sets more efficient than lists? ›

Since sets do not store indexed data or duplicates, they use less memory than lists and are less computationally expensive. As a result, sets take less time to search through.

Why use a set instead of a list? ›

The main difference between List and Set is that List allows duplicates while Set doesn't allow duplicates.

Can a set be infinite? ›

An infinite set is a set whose elements can not be counted. An infinite set is one that has no last element. An infinite set is a set that can be placed into a one-to-one correspondence with a proper subset of itself.

Can a set have nothing in it? ›

In mathematical sets, the null set is a set that does not contain any values or elements. It is expressed as { } and denoted using the Greek letter ∅ (phi). A null set is also known as an empty set or void set. There is only one null set because, logically, there's only one way that a set can contain nothing.

What does ⊆ mean in sets? ›

The symbol "⊂" means "is a proper subset of". Example. Since all of the members of set A are members of set D, A is a subset of D.

How do you explain sets? ›

In Maths, sets are a collection of well-defined objects or elements. A set is represented by a capital letter symbol and the number of elements in the finite set is represented as the cardinal number of a set in a curly bracket {…}.

Does order matter in sets? ›

The order of elements in the set does not matter. We could just as well write S = {N ader, Buchanan, Gore, Bush}. In general, two sets are the same if and only if they have exactly the same members. “Gore ∈ S” reads “Gore is a member of the set S.” “∈” means “is a member of” or “is in”.

Can a set have 2 same elements? ›

"A set has no duplicate elements. An element is either a member of a set or not. It cannot be in the set twice."

Are sets immutable in Python? ›

Set Items. Items of a set in python are immutable (unchangeable), do not duplicate values, and unordered. Thus, items in a set do not appear in a stipulated manner, i.e., they can appear in a different order every time it is used. Due to this, set items cannot be referred to by key or index.

How do you get a set value in Python? ›

You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

How do you add values to a set in Python? ›

You can add an item to a set in Python by using the add() method with the new item to be added passed in as a parameter.

Does set () work on strings? ›

We can convert a string to setin Python using the set() function. Parameters : Any iterable sequence like list, tuple or dictionary.

How do we use sets in real life? ›

We all have a group of some objects, collection of our favorite things, sets of books, a list of cities and countries in our life.
...
7 Daily Life Examples Of Sets
• In Kitchen. Kitchen is the most relevant example of sets. ...
• School Bags. ...
• Shopping Malls. ...
• Universe. ...
• Playlist. ...
• Rules. ...
• Representative House.

Are sets always ordered? ›

A set isn't ordered unless you supply an ordering. A set on its own is not an ordered set.

What is the rule of set? ›

Both the universal set and the empty set are subsets of every set. Rule is a method of naming a set by describing its elements. { x: x > 3, x is a whole number} describes the set with elements 4, 5, 6,…. Therefore, { x: x > 3, x is a whole number} is the same as {4,5,6,…}.

What is set formula? ›

What Is the Formula of Sets? The set formula is given in general as n(A∪B) = n(A) + n(B) - n(A⋂B), where A and B are two sets and n(A∪B) shows the number of elements present in either A or B and n(A⋂B) shows the number of elements present in both A and B.

What are the 4 types of functions? ›

There are 4 types of functions:
• Functions with arguments and return values. This function has arguments and returns a value: ...
• Functions with arguments and without return values. ...
• Functions without arguments and with return values. ...
• Functions without arguments and without return values.

Is A set an array? ›

One of the biggest differences between an Array and a Set is the order of elements. The documentation describes this as well: Array: “An ordered, random-access collection.” Set: “An unordered collection of unique elements.”

What is set in data type? ›

In computer science, a set is an abstract data type that can store unique values, without any particular order. It is a computer implementation of the mathematical concept of a finite set.

What data structure is set? ›

A set is a data structure that stores unique elements of the same type in a sorted order. Each value is a key, which means that we access each value using the value itself. With arrays, on the other hand, we access each value by its position in the container (the index). Accordingly, each value in a set must be unique.

What is not a set example? ›

The things which are not certain or well – defined, they cannot form a set as a set needs to be definite such as all the birds in the sky, all the notes in a bank, members of Indian basketball team are such examples which cannot constitute a set since all of them are indefinite.

Is the following true or false ∅ ⊂ ∅? ›

(i) ∅ ∈ ∅. Answer. False; there are no elements in the empty set.

Is an empty set True or false? ›

(b) True. The empty set is a subset of every set.

What are the 4 operations of sets? ›

The four important basic operations of sets are :
• Union of sets.
• Intersection of sets.
• Complement of sets.
• Cartesian product of sets.

What are the 5 types of sets? ›

The empty set, finite set, equivalent set, subset, universal set, superset, and infinite set are some types of set.

How many types of sets are there? ›

Q. 3 How many types of sets are there? Ans. 3 The different types of sets are empty set, finite set, singleton set, equivalent set, subset, power set, universal set, superset and infinite set.

What data structure is a set in Python? ›

Set is a Data Structure in Python with an unordered and unindexed collection of elements. Every element in a Set is always unique. The Set Data Structure does not allow any duplication of elements. The Set is similar to the list Data Structure when it comes to mutability.

Is set an object in Python? ›

A set is a mutable collection of distinct hashable objects, same as the list and tuple. It is an unordered collection of objects, meaning it does not record element position or order of insertion and so cannot access elements using indexes.

Does Python support set? ›

Grouping objects into a set can be useful in programming as well, and Python provides a built-in set type to do so. Sets are distinguished from other object types by the unique operations that can be performed on them.

How do you create a set in Python? ›

Create a Set in Python

In Python, we create sets by placing all the elements inside curly braces {} , separated by comma. A set can have any number of items and they may be of different types (integer, float, tuple, string etc.).

Are sets used in coding? ›

In computer science, a set is an abstract data type that will store an unordered collection of unique values. In many programming languages, sets are implemented as built-in data structures, similar to arrays or dictionaries.

Are sets iterable in Python? ›

In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. There are numerous ways that can be used to iterate over a Set.

Is set comprehension possible in Python? ›

Python supports the following 4 types of comprehensions: List Comprehensions. Dictionary Comprehensions. Set Comprehensions.

Can set have duplicates? ›

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

What is a set in coding? ›

A set is a data structure that stores unique elements of the same type in a sorted order. Each value is a key, which means that we access each value using the value itself. With arrays, on the other hand, we access each value by its position in the container (the index). Accordingly, each value in a set must be unique.

How do you define a set? ›

Intuitively, a set is a collection of objects, considered as a whole. The objects that make up the set are called its elements or its members. The elements of a set may be any objects whatsoever, but for our purposes, they will usually be mathematical objects such as numbers, functions, or other sets.

Why sets are useful in programming? ›

A set is a data structure that can store any number of unique values in any order you so wish. Set's are different from arrays in the sense that they only allow non-repeated, unique values within them.

Why do we use sets? ›

Sets are used to store a collection of linked things. They are essential in all fields of mathematics because sets are used or referred to in some manner in every branch of mathematics. They are necessary for the construction of increasingly complicated mathematical structures.

Is coding all math? ›

While some fields of programming require you to have extensive knowledge of mathematics (such as game development and machine learning), you don't need advanced math skills for most coding jobs.

Does set allow duplicates in Python? ›

Sets do not allow duplicate items, they are unordered, and the items stored in them cannot be modified.

Why set doesn t allow duplicates in Python? ›

Sets cannot contain duplicates. Duplicates are discarded when initializing a set. If adding an element to a set, and that element is already contained in the set, then the set will not change.

Is set sequential in Python? ›

Yes, set is a set of elements, there is no order for "set".

Videos

1. Real Python's Quiz on Sets
(Oscar Sheen)
2. Python Wheels and Pass by Reference in Python | Real Python Podcast #23
(Real Python)
3. Where to Find Real-World Python Projects
(Real Python)
4. Python Decorators and Writing for Real Python | Real Python Podcast #1
(Real Python)
5. What are Sets in Python - Explained with Examples | Python Tutorial
(WsCube Tech)
6. Learn Python for Data Science (with Real Python)
(Data Professor)
Top Articles
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated: 12/14/2022

Views: 6013

Rating: 4.2 / 5 (43 voted)

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.