Set in Python with Examples

set in python

Hello Techies,

This blog is about “Set in Python”. A set is a Python’s Built-in data type that allows you to store unique data types in it. So in this blog, we will learn about the usage of the Set in Python.

Check my previous blog, I covered built-in datatypes in Python topic.

Let’s start and check, How to use Set in Python step by step.

Below are the Key Points of Set in Python that we are covering in this blog.

  1. Python Set (Introduction)
  2. Create Set in Python
  3. Create an empty set in Python
  4. Add or Update Set Element
  5. Delete or Remove elements from Set
  6. Python Set Methods
  7. Python Set Operations
  8. Python Frozenset

#1. Python Set(Introduction)

  • The use of Set in python is to store the Unique element.
  • Set is an unordered collection data type that is mutable.
  • Because sets are unordered, we cannot access items using indexes.
  • Set is mutable so we can modify its element.
  • Sets can be used to perform mathematical set operations such as union, intersection point, etc.
  • The set is represented using curly braces { }.
  • Example: data = {1, -89, “test”, “TechPlusLifeStyle”}

#2. Create Set in Python

A set can have many objects and can be of different types (such as strings, integers, floats, tuples, etc.). The set does not include mutable elements like dictionaries and lists.

The set can be created using the built-in set() function as well as you can place objects in curly braces. Check the below example.

Syntax

set_name = {item1, item2, item3, ...}
set_function = set([item1, item2, item3, ...])

Example

data = {1, -89, "test", "TechPlusLifeStyle"}
data_using_set_fun = set([1, -89, "test", "TechPlusLifeStyle"])

#3. Create an empty set in Python

Creating an empty set in Python is a bit difficult because empty curly brackets ({ }) in Python create an empty dictionary. We use the set() function without any argument to create an empty set in Python.

Example

data = {}
type(data)

# empty set
data = set()
type(data)

Output

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

#4. Add or Update Set Element

The Set is mutable so we can modify its element. However, the sets are unordered collections so we cannot modify any elements from the set.

We can use the add() method to add any single element to the set or add multiple elements using the update() method.

data = {1, -89, "test", "TechPlusLifeStyle"}
data.add(2)
print(data)

data.update([5,8])
print(data)

data.update([7, 0], {-8, "test"})
print(data)

Output

{1, 2, "TechPlusLifeStyle", -89, "test"}
{1, 2, 5, "TechPlusLifeStyle", -89, 8, "test"}
{0, 1, 2, 5, "TechPlusLifeStyle", -89, 8, 7, -8, "test"}

#5. Delete or Remove elements from Set

We can use 2 different methods (remove() and discard()) to remove specific elements from the set.

The main difference between both are, The discard() function keeps the set unchanged if the element is not in the set, and The Remove() function will raise an error in this case (if the element is not present in the set).

# discard method
data = {'p', 'w', 'o', 'a', 'g', 'e', 'm'}
data.discard('p')
print(data)

# remove method
data.remove('o')
print(data)

# discard element which not present in set
data.discard('q')
print(data)

# remove element which not present in set
data.remove('z')

Output

{'w', 'm', 'a', 'g', 'o', 'e'}  
{'w', 'm', 'a', 'g', 'e'}  
{'w', 'm', 'a', 'g', 'e'} 
Traceback (most recent call last):                                                                                        File "<stdin>", line 1, in <module>                                                                                   KeyError: 'z'  

We can also use the pop() method to remove elements from the set.

Set is an unordered data type, so there is no way to determine which item will pop up. It is completely arbitrary.

The pop() method removes and returns the item. We can also use the clear() method to clear the set.

my_set = {'a','b','c','d','e','f','g'}

print(my_set.pop())
print(my_set)

my_set.clear()
print(my_set)

Output

a
{'f', 'c', 'd', 'g', 'b', 'e'} 
set()

Interview question

Q: Difference between list and set in python?

Ans: 1) The list is an ordered collection of items, but the set is an unordered 
             collection of items.
        2) The items in the list can be changed or replaced, but  items in the set
            can not be changed or replaced.

Q: Difference between set and dictionary in python?

Ans: Dictionaries and sets are almost identical, except that these sets have no 
        values: a set is just a collection of unique keys. As the name suggests, 
        sets are very useful for performing set operations.

#6. Python Set Methods

The methods available with the set objects in Python programming are in the table below.

Method NameDescription
add()Add an element to the set
copy()Returns a copy of the set
difference()Returns the difference between two or more sets as a new set
difference_update()This method remove all elements of another set from this set
discard()If an element is a member, it is removed from the set.
clear()Removes all elements from the set
intersection()This method returns the intersection of two sets as a new set
intersection_update()Updates the set with intersection of itself and others
isdisjoint()If there is null intersection between the two sets, it returns True
issubset()This method returns True if another set contains this set
issuperset()If there is another set in this set it returns the True
pop()Removes and retrieves an arbitrary set element. If the set is empty, it Raises KeyError.
symmetric_difference()Returns symmetrical differences between the two sets as a new set
symmetric_difference_update()Updates the set with its own and other’s symmetrical differences
union()Returns a match of sets in a new set
remove()Removes an element from the set. If the element is not a member, it will raises a KeyError
update()This method updates the set with the union of itself and others

Some examples of Python methods

data = {4, 8, 1, 6, 8}

# add() method
data.add(7)
print(data)

# copy() method
data1 = {2, 3}  
data1.copy()
print(data1)

# issuperset() method
x = {1, 2, 3, 4, 5}
y = {1, 2, 3}

# Returns True
print(x.issuperset(y))


# intersection() method
x = {1, 2, 3, 4, 5}
y = {1, 2, 3}

z = x.intersection(y)
print(z)

Output

{1, 4, 6, 7, 8} 
{1, 4, 6, 7, 8}  
{1, 4, 6, 7, 8}  
True 
{1, 2, 3} 

#7. Python Set Operations

Sets can be used to perform mathematical sets such as union, intersection, difference, and symmetrical difference.

Let’s check Python Set operations.

Let us consider the following two sets for further operations.

x = {1, 2, 3, 4, 6}
y = {2, 4, 9, 7, 8}

Set Union

Union x and y are a set of all the elements in both sets. This can be done using the Operator Union() method and | operator.

x = {1, 2, 3, 4, 6}
y = {2, 4, 9, 7, 8}

print(x | y)
print(x.union(y))

Output

{1, 2, 3, 4, 6, 7, 8, 9}  
{1, 2, 3, 4, 6, 7, 8, 9} 

Set Intersection


The intersection of x and y is a set of elements that is common to both sets. This can be done using the Operator intersection() method and & operator.

x = {1, 2, 3, 4, 6}
y = {2, 4, 9, 7, 8}

print(x & y)
print(x.intersection(y))

Output

{2, 4}
{2, 4}

Set Difference

The difference of set y from set x (x – y) is the set of elements that is present only in x but not in y. Similarly, y – x is a set of elements in y but not in x

This can be done using the Operator difference() method and – operator.

x = {1, 2, 3, 4, 6}
y = {2, 4, 9, 7, 8}

print(x - y)
print(x.difference(y))

Output

{1, 3, 6} 
{1, 3, 6} 

Set Symmetric Difference

The symmetrical difference of x and y is a set of elements in x and y but not in both. This can be done using the Operator symmetric_difference() method and ^ operator.

x = {1, 2, 3, 4, 6}
y = {2, 4, 9, 7, 8}

print(x ^ y)
print(x.symmetric_difference(y))
{1, 3, 6, 7, 8, 9} 
{1, 3, 6, 7, 8, 9} 

#8. Python Frozenset

frozenset is a new class that has set features, but its elements cannot be changed once assigned.

Sets that are mutable are unhashable, so they cannot be used as a dictionary key. Frozen, on the other hand, are hashable and can be used as a dictionary key.

Frozensets can be created using the frozenset() function. This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union()

Example

x = frozenset([1, 2, 3])
y = frozenset([3, 4, 5, 7]
x.union(y)
x | y

Output

frozenset({1, 2, 3, 4, 7, 8, 9}) 
frozenset({1, 2, 3, 4, 7, 8, 9}) 

I hope you understand the use of “Set in Python”. Still, you have any doubts please comment below.

Check out the official site for more details on “Set in Python”.

Leave a Comment