Python Set



Set

A set is a collection of items that is both unordered and unindexed.

A set is used to store multiple items in a single variable.

Sets can also be used to perform mathematical set operations like union, interaction, difference, etc.

A 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.


How to Create a Set?

A set can be created by placing items inside curly braces {}, separated by a comma, or using the built-in set() function.

A set can have any number of items, and it can be of different types (integer, float, string, tuple, etc.). However, a set cannot have mutable elements like lists, sets, or dictionaries as its elements.

# set of integers
my_set = {6, 8, 10}
print(my_set)

# set of mixed datatypes
my_set = {7, 6.0, "Hi", (6, 7, 8, 9)}
print(my_set)

# set cannot have duplicates
my_set = {1, 1, 1, 2, 2, 3, 4, 4}
print(my_set)

# we can make a set from a list
my_set = set([1, 2, 3, 4, 3, 3])
print(my_set)

# a set cannot have mutable items
# this will raise an error
my_set = {1, 2, 3, [4, 5, 6]}

Output

{8, 10, 6}
{'Hi', (6, 7, 8, 9), 6.0, 7}
{1, 2, 3, 4}
{1, 2, 3, 4}

TypeError  Traceback (most recent call last)
---> 19 my_set = {1, 2, 3, [4, 5, 6]}
TypeError: unhashable type: 'list'

How to Create an Empty Set?

Creating an empty set is a little bit different.

In Python, when using empty curly braces {}, it will create an empty dictionary.

To create an empty set, you can use the set() function without any arguments.

# creating an empty dictionary
my_dict = {}

print(type(my_dict))

# creaing an empty set
my_set = set()

print(type(my_set))

Output

<class 'dict'>
<class 'set'>

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.


Unordered

Set items are unordered, which means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them.

Set items cannot be referred to by index or key.


Unchangeable

Set items are unchangeable, meaning you cannot change the items after the set has been created.

Note: When a set is created, you cannot change its items. However, you can add new items.


Duplicates Not Allowed

Sets do not allow two items with the same value.

In the following example, we will see that duplicate values will be ignored on a set.

my_set = {1 , 2 , 1, 3, 3, 4, 3}

print(my_set)

Output

{1, 2, 3, 4}

Length of a Set

You can use the len() function to determine how many items a set has.

In the following example, we will get the number of items in a set.

my_set = {1, 3, 5, 7, 9}

print(len(my_set))

Output

5

Set Items - Data Types

Set items can be of any data type. But, they cannot be mutable elements like lists, sets, or dictionaries.

my_set1 = {1, 9, 17, 7, 46}
my_set2 = {"kiwi", "apple", "blueberry", "dragonfruit"}
my_set3 = { True, True, False, True}

print(my_set1)
print(my_set2)
print(my_set3)

Output

{1, 7, 9, 46, 17} 
{'apple', 'blueberry', 'dragonfruit', 'kiwi'} 
{False, True}

The same set can contain different data types.

In the following example, we will create a set with integers, strings, and boolean values.

my_set = {45, "Hello", 14, True, "python", False}

print(my_set)

Output

{'python', True, False, 45, 14, 'Hello'}

type()

In Python, a set is defined as objects with the data type 'set'.

my_set = {1, 9, 17, 7, 46}

print(type(my_set))

Output

<class 'set'>

The set() Constructor

You can also use the set() constructor to create a set.

In the following example, we will use the set() constructor to create a set.

my_set = set(("kiwi", "apple", "blueberry", "dragonfruit"))

print(my_set)

Output

{'apple', 'blueberry', 'dragonfruit', 'kiwi'}

Access Set Items

Set items cannot be accessed by referring to an index or a key.


Access Items

To access a set of items, you can use a for loop to loop through them.

my_set = {"kiwi", "apple", "blueberry", "dragonfruit"}

for x in my_set:
    print(x)

Output

dragonfruit
kiwi
blueberry
apple

To check if a specified value is present in a set, you can use the in keyword.

my_set = {"kiwi", "apple", "blueberry", "dragonfruit"}

if "blueberry" in my_set:
    print("Yes, blueberry is present in the set")

Output

Yes, blueberry is present in the set

Change Items

Once a set is created, its items cannot be changed, but you can add new items.


Add Set Items

After creating a set, it's impossible to change its items, but you can add new items.

There are different ways that you can use to add new items to a set.


Add Items

You can add a new item to a set using the add() method.

In the following example, we will add a new item to a set using the add() method.

my_set = {"kiwi", "apple", "blueberry"}

my_set.add("dragonfruit")

print(my_set)

Output

{'dragonfruit', 'kiwi', 'blueberry', 'apple'}

Add Sets

You can add items from another set into the current set using the update() method.

In the following example, we will add elements from "my_set2" to "my_set1".

my_set1 =  {"kiwi", "apple", "blueberry"}
my_set2 = {"strawberry", "orange", "watermelon"}

my_set1.update(my_set2)

print(my_set1)

Output

{'kiwi', 'strawberry', 'watermelon', 'orange', 'apple', 'blueberry'}

Add Any Iterable

You can also use the update() method to add any iterable object like lists, sets, tuples, dictionaries, strings, etc.

In the following example, we will add items of a list to a set.

my_set =  {"kiwi", "apple", "blueberry"}
my_list = ["strawberry", "orange", "watermelon"]

my_set.update(my_list)

print(my_set)

Output

{'kiwi', 'apple', 'watermelon', 'blueberry', 'strawberry', 'orange'}

Remove Set Items

There are different ways that you can use to remove items from a set.


Remove Item

You can use the remove() or the discard() method to remove an item in a set.

In the following example, we will remove the "blueberry" using the remove() method.

my_set = {"kiwi", "apple", "blueberry", "dragonfruit"}

my_set.remove("blueberry")

print(my_set)

Output

{'apple', 'dragonfruit', 'kiwi'}

Note: When using a remove() method, an error will be raised if the item to remove does not exist.

In the following example, we will remove the "blueberry" using the discard() method.

my_set = {"kiwi", "apple", "blueberry", "dragonfruit"}

my_set.discard("blueberry")

print(my_set)

Output

{'apple', 'dragonfruit', 'kiwi'}

Note: When using a discard() method, No error will be raised if the item to remove does not exist.

You can also use the pop() method to remove the last item from a set. But, knowing that sets are unordered, you will not know which item is getting removed.

The return value of the pop() method is the removed item.

In the following example, we will remove the last item using the pop() method.

my_set = {"kiwi", "apple", "blueberry", "dragonfruit"}

x = my_set.pop()

print(x)

Output

apple

Note: When using the pop() method in a set, you will not know which item will be removed due to the sets are unordered.


Clear Set

To empty a set, you can use the clear() method.

After clearing a set, the set will remain, but it will not have any content.

In the following example, we will use clear() to empty a set.

my_set = {"kiwi", "apple", "blueberry", "dragonfruit"}

my_set.clear()

print(my_set)

Output

set()

If you want to delete the set completely, you can use the del keyword.

In the following example, we will use the del keyword to delete the set.

my_set = {"kiwi", "apple", "blueberry", "dragonfruit"}

del my_set

print(my_set)

Output

NameError  Traceback (most recent call last)
      3 del my_set
      4 
----> 5 print(my_set)

NameError: name 'my_set' is not defined

Iterating Through a Set

You can iterate through each item in a set using a for loop.

In the following example, we will loop through a set and print the values.

my_set = {"kiwi", "apple", "blueberry"}

for x in my_set:
    print(x)

Output

apple
kiwi
blueberry

Python Set Operations

Sets can carry out mathematical set operations like a union, intersection, difference, and symmetric difference. You can use mathematical set operations with operators or methods.


Set Union

set union in python

The Union of A and B is a set of all items from both sets.

You can perform a union using the | operator or using the union() method.

# initialize a and b
a = {"a", "b", "c", "d"}
b = {1, 2, 3, 4}

# use | operator 
print(a | b)

# use union function on a
print(a.union(b))

# use union function on b
print(b.union(a))

Output

{1, 'a', 2, 3, 'c', 4, 'b', 'd'}
{1, 'a', 2, 3, 'c', 4, 'b', 'd'}
{1, 2, 3, 4, 'a', 'c', 'b', 'd'}

Note: Using the union() method will exclude any duplicate items.


Set Intersection

set interaction in python

Intersection of A and B is a set of items that are common in both sets.

You can perform an intersection using the & operator or using the intersection() method.

# initialize a and b
a = {"a", "b", "c", "d"}
b = {"e", "d", "b", "f", "c"}

# use & operator 
print(a & b)

# use intersection function on a
print(a.intersection(b))

# use intersection function on b
print(b.intersection(a))

Output

{'b', 'c', 'd'} 
{'b', 'c', 'd'}
{'b', 'c', 'd'}

Set Difference

set difference in python

Difference of the set B from set A (A - B) is a set of items that are only in A but not in B. Similarly, B - A is a set of items in B but not in A.

You can perform a difference using the - operator or using the difference() method.

# initialize a and b
a = {"a", "b", "c", "d", "k"}
b = {"e", "d", "b", "f"}

# use - operator 
print(a - b)

# use difference function on a
print(a.difference(b))

# use difference function on b
print(b.difference(a))

Output

{'a', 'c', 'k'} 
{'a', 'c', 'k'} 
{'e', 'f'}

Set Symmetric Difference

set symmetric difference in python

Symmetric Difference of A and B is a set of items in A and B but not in both (excluding the intersection).

You can perform a symmetric difference using the ^ operator or using the symmetric_difference() method.

# initialize a and b
a = {"a", "b", "c", "d", "k"}
b = {"e", "d", "b", "f"}

# use ^ operator 
print(a ^ b)

# use symmetric difference function on a
print(a.symmetric_difference(b))

# use symmetric difference function on b
print(b.symmetric_difference(a))

Output

{'a', 'c', 'k', 'e', 'f'} 
{'a', 'c', 'k', 'e', 'f'} 
{'a', 'e', 'f', 'c', 'k'}

Set Methods

Python offers different built-in methods that you can use on sets.

Method Description
add() It is used to add an item to the set
clear() It is used to remove all the items from the set
copy() It is used to return a copy of the set
difference() It is used to return a set containing the difference between two or more sets
difference_update() It is used to remove the items in this set that are also included in another, specified set
discard() It is used to remove the specified item
intersection() It is used to return a set, that is the intersection of two sets
intersection_update() It is used to remove the items in this set that are not present in other, specified set(s)
isdisjoint() It is used to return whether two sets have an intersection or not
issubset() It is used to return whether another set contains this set or not
issuperset() It is used to return whether this set contains another set or not
pop() It is used to remove an item from the set
remove() It is used to remove the specified item
symmetric_difference() It is used to return a set with the symmetric differences of two set
symmetric_difference_update() It is used to insert the symmetric differences from this set and another
union() It is used to return a set containing the union of sets
update() It is used to update the set with the union of this set and others


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.