What does set () set () mean in Python?

If you're a beginner to Python, chances are you've come across lists. But have you heard about sets in Python?

In this tutorial, we'll explore what sets are, how to create them, and the different operations you can use on them.

What are sets in Python?

In Python, sets are exactly like lists except for the fact that their elements are immutable (that means you cannot change/mutate an element of a set once declared). However, you can add/remove elements from the set.

If that was confusing, let me try and summarize:

A set is a mutable, unordered group of elements, where the elements themselves are immutable.

Another characteristic of a set is that it may include elements of different types. This means you can have a group of numbers, strings, and even tuples, all in the same set!

How to Create a Set

The most common way of creating a set in Python is by using the built-in

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
5 function.

>>> first_set = set(("Connor", 32, (1, 2, 3)))
>>> first_set
{32, 'Connor', (1, 2, 3)}
>>> 
>>> second_set = set("Connor")
>>> second_set
{'n', 'C', 'r', 'o'}

You can also create sets using the curly brace

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
6 syntax:

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)

The

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
5 function takes in an iterable and yields a list of objects which will be inserted into the set. The
>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
6 syntax places the objects themselves into the set.

As you've probably realized, whether you use the

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
5 function or the
>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
6 to create a set, each element needs to be an immutable object. So if you add a list (which is a mutable object) to a set, you'll run into an error:

>>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
How to Add or Remove Elements in a Set

We already know that sets are mutable. This means you can add/remove elements in a set.

Here's an example of adding elements to a set using the

>>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
1 function.

>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}

But notice how nothing changes when we try to add "cello" to the set again:

>>> add_set.update(("cello",))
>>> add_Set
{1, 2, 3, 4, 'violin', 'cello'}

This is because sets in Python cannot contain duplicates. So, when we tried to add

>>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
2 again to the set, Python recognized we were trying to add a duplicate element and didn't update the set. This is one caveat that differentiates sets from lists.

Here's how you would remove elements from a set:

>>> sub_set = add_set
>>> sub_set.remove("violin")
>>> sub_set
{1, 2, 3, 4, 'cello'}

The

>>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
3 function removes the element
>>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
4 from a set. It returns a
>>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
5 if
>>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
4 is not part of the set:

>>> sub_set.remove("guitar")
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'guitar'

There are a couple of other ways to remove an element(s) from a set:

  • the
    >>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'list'
    
    7 method removes
    >>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'list'
    
    4 from the set, but doesn't raise any error if
    >>> incorrect_set = {"Apples", ["Bananas", "Oranges"]}
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'list'
    
    4 is not present in the set.
  • the
    >>> add_set = set((1, 2, 3, 4))
    >>> add_set
    {1, 2, 3, 4}
    >>>
    >>> add_set.update((1,))
    >>> add_set
    {1, 2, 3, 4}
    >>> add_set.update(("cello", "violin"))
    >>> add_set
    {1, 2, 3, 4, 'violin', 'cello'}
    0 method removes and returns a random element from the set.
  • the
    >>> add_set = set((1, 2, 3, 4))
    >>> add_set
    {1, 2, 3, 4}
    >>>
    >>> add_set.update((1,))
    >>> add_set
    {1, 2, 3, 4}
    >>> add_set.update(("cello", "violin"))
    >>> add_set
    {1, 2, 3, 4, 'violin', 'cello'}
    1 method removes all elements from a set

Here are some examples to illustrate:

>>> m_set = set((1, 2, 3, 4))
>>> 
>>> m_set.discard(5) # no error raised even though '5' is not present in the set
>>>
>>> m_set.pop()
4
>>> m_set
{1, 2, 3}
>>>
>>> m_set.clear()
>>> m_set
set()
Python set() Operations

If you remember your basic high school math, you'll probably recall mathematical set operations like union, intersection, difference and symmetric difference. Well, you can achieve the same thing with Python sets.

1. Set Union

The union of two sets is the set of all the elements of both the sets without duplicates. You can use the

>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
2 method or the
>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
3 syntax to find the union of a Python set.

>>> first_set = {1, 2, 3}
>>> second_set = {3, 4, 5}
>>> first_set.union(second_set)
{1, 2, 3, 4, 5}
>>>
>>> first_set | second_set     # using the `|` operator
{1, 2, 3, 4, 5}

2. Set Intersection

The intersection of two sets is the set of all the common elements of both the sets. You can use the

>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
4 method of the
>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
5 operator to find the intersection of a Python set.

>>> first_set = {1, 2, 3, 4, 5, 6}
>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.intersection(second_set)
{4, 5, 6}
>>>
>>> first_set & second_set     # using the `&` operator
{4, 5, 6}

3. Set Difference

The difference between two sets is the set of all the elements in first set that are not present in the second set. You would use the

>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
6 method or the
>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
7 operator to achieve this in Python.

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
0

4. Set Symmetric Difference

The symmetric difference between two sets is the set of all the elements that are either in the first set or the second set but not in both.

You have the choice of using either the

>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
8 method or the
>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
9 operator to do this in Python.

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
1How to Modify a Set by Operations

Each of the

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
5 operations that we discussed above can be used to modify an existing Python set. Similar to how you would use an augmented assignment syntax such as
>>> add_set.update(("cello",))
>>> add_Set
{1, 2, 3, 4, 'violin', 'cello'}
1 or
>>> add_set.update(("cello",))
>>> add_Set
{1, 2, 3, 4, 'violin', 'cello'}
2 to update a variable, you can do the same for sets:

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
2Other Set Operations in Python

These are not so common, but they're useful in seeing how sets relate to others.

  • the
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    3 method or
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    4 operator returns true if the
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    5 is a subset of
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    6
  • the
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    7 method or
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    8 operator returns true if the
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    5 is a superset of
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    6
  • the
    >>> sub_set = add_set
    >>> sub_set.remove("violin")
    >>> sub_set
    {1, 2, 3, 4, 'cello'}
    1 method return true if there are no common elements between sets
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    5 and
    >>> add_set.update(("cello",))
    >>> add_Set
    {1, 2, 3, 4, 'violin', 'cello'}
    6
Frozen Sets in Python

Because sets are mutable, they are unhashable – which means you cannot use them as dictionary keys.

Python allows you to work around this by using a

>>> sub_set = add_set
>>> sub_set.remove("violin")
>>> sub_set
{1, 2, 3, 4, 'cello'}
4 instead. This has all the properties of a set, except that it is immutable (this means that you cannot add/remove elements from the frozenset). It is also hashable, so it can be used as keys to a dictionary.

The

>>> sub_set = add_set
>>> sub_set.remove("violin")
>>> sub_set
{1, 2, 3, 4, 'cello'}
4 datatype has all the methods of a set (such as
>>> add_set = set((1, 2, 3, 4))
>>> add_set
{1, 2, 3, 4}
>>>
>>> add_set.update((1,))
>>> add_set
{1, 2, 3, 4}
>>> add_set.update(("cello", "violin"))
>>> add_set
{1, 2, 3, 4, 'violin', 'cello'}
6,
>>> sub_set = add_set
>>> sub_set.remove("violin")
>>> sub_set
{1, 2, 3, 4, 'cello'}
7, and
>>> sub_set = add_set
>>> sub_set.remove("violin")
>>> sub_set
{1, 2, 3, 4, 'cello'}
8) but because it is immutable, it doesn't have methods to add/remove elements.

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
3

And using

>>> sub_set = add_set
>>> sub_set.remove("violin")
>>> sub_set
{1, 2, 3, 4, 'cello'}
4s as dictionary keys is as simple as 1, 2, 3:

>>> third_set = {"Apples", ("Bananas", "Oranges")}
>>> type(third_set)
4Wrapping Up

That's it! You've learned about what sets are, how to create and work with them, and different operations you can use on them.

With sets done, you should now be comfortable with most of Python built-in functions. All you need to do now is practice. Good luck!

Be sure to follow me on Twitter for more updates. Have a nice one!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


What does set () set () mean in Python?
Jason Dsouza

AI Researcher @Harvard, Teacher @freeCodeCamp. Part-time Compiler Warlock.


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

What does set () do in Python?

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

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.

What is set and set operations in Python?

Python set() Operations.
Set Union. The union of two sets is the set of all the elements of both the sets without duplicates. ... .
Set Intersection. The intersection of two sets is the set of all the common elements of both the sets. ... .
Set Difference. ... .
Set Symmetric Difference..

Can you set of set in Python?

To represent a set of sets, the inner sets must be frozenset objects for the reason that the elements of a set must be hashable (all of Python's immutable built-in objects are hashable). frozenset is immutable and set is mutable.