Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (83 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

What are Sets in Python and How to use them?

Last updated on Nov 26,2019 4.6K Views

26 / 62 Blog from Python Fundamentals

Data storage is something that is necessary for every domain in today’s world. Python provides different types of data structures to organize your data and these data structures are an essential part of Python Certification Training. Among all data structures available in Python, some are mutable and some are immutable. In this article, I will be discussing one of these i.e sets. Sets in Python are data structures that are mutable, iterable and unordered. Here is a quick walkthrough of all that has been covered further.

What is Set in Python?
When to use sets in Python? 
How do you create a set?
Set Operations

What are Frozen Sets?

Let’s get started. :-)

What is Set in Python?

A set is basically a data type consisting of a collection of unordered elements. These elements can be on any data types as sets, unlike arrays, are not type specific. Sets are mutable(changeable) and do not have repeated copies of elements. The values of a set are unindexed, therefore, indexing operations cannot be performed on sets.

Example:

My_Set={1,'s',7.8}
print(My_Set)

Output:  {‘s’, 1, 7.8}

The output shows all the elements present My_Set.

Note: A set as a whole is mutable but the elements of a set are not.

Now that you know what are sets in Python, let’s move ahead and understand when to use sets.

When to use sets in Python?

Sets in Python are used when-

  • The order of data does not matter
  • You do not need any repetitions in the data elements
  • You need to perform mathematical operations such as union, intersection, etc

Now let us move ahead and see how to create sets in Python.

How do you create a set in Python?

Sets in Python can be created in two ways-

  • enclosing elements within curly braces
  • by using the set() function

1.Using curly braces:

Sets in Python are created using curly braces({}).

Example: 
My_Set={1,'s',7.8}
print(My_Set)

Output:    {‘s’, 1, 7.8}

As you can see, My_Set has been created.

2. Using set() function

Sets in Python can be created using the set() function.

Example: 

a=set({1,'b',6.9})
print(a)

Output:  {1, ‘b’, 6.9}

You can also create an empty set using the same function.

Example:

Empty_Set=set()
print(Empty_Set)

Output: set()

The above output shows an empty set named Empty_Set has been created.

You can add elements to this empty set. I will be covering that in the following topics.

Set Operations

A number of operations can be performed on sets such as adding elements, deleting elements, finding the length of a set, etc. To know what all methods can be used on sets, you can use the dir() function.

Example:

My_Set={1,'s',7.8}
dir(My_Set)

Output: 

[‘__and__’,’__class__’,’__contains__’,’__delattr__’,’__dir__’,’__doc__’,’__eq__’,’__format__’,’__ge__’,’__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__iand__’, ‘__init__’, ‘__init_subclass__’, ‘__ior__’, ‘__isub__’, ‘__iter__’, ‘__ixor__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__or__’, ‘__rand__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__ror__’, ‘__rsub__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__xor__’, ‘add’, ‘clear’, ‘copy’, ‘difference’, ‘difference_update’, ‘discard’, ‘intersection’, ‘intersection_update’, ‘isdisjoint’, ‘issubset’, ‘issuperset’, ‘pop’, ‘remove’, ‘symmetric_difference’, ‘symmetric_difference_update’, ‘union’, ‘update’]

The output shows all the methods that can be used on sets. I will be demonstrating a few of them further in this article.

Finding the Length of a Set

To find the length of a set in Python, you can use the len() function. This function takes the name of the set as a parameter and returns an integer value which is equal to the number of elements present in the set.

Example:

My_Set={1,'s',7.8}

len(My_Set)

Output: 3

As you can see in the above output, 3 has been returned which equal to the number of elements present in My_Set. Now, these elements can be accessed as well, which is shown below.

Accessing Elements of a Set

Set elements cannot be accessed using the index numbers because, as specified before, elements of a set are not indexed. Therefore, when you want to access elements of a set, you can loop through it and access its elements.

Example:

My_Set={1,'s',7.8}
for x in My_Set:
    print(x)

Output:

s
1
7.8

As you can see in the output, the order is different than the order of elements supplied to the set. This is because the elements are not ordered. 

Adding elements to a Set:

Elements can be added to a set using two functions, the add() and the update() function.

The add() function adds one element to the existing set as shown below:

Example:

My_Set={1,'s',7.8}
My_Set.add(3)
My_Set

Output: {1, 3, 7.8, ‘s’}

The update() function is used when you want to add more than one element to the existing set.

Example:

My_Set={1,'s',7.8}
My_Set.update([2,4.6,1,'r'])
My_Set

Output:  {1, 2, 4.6, 7.8, ‘r’, ‘s’}

As you can see in the above output, the update() function is taking a list of 4 values and all values except 1 are added to My_Set. This is because 1 is already present in the set and therefore, it cannot be added again. 

Removing Elements of a Set

To remove elements from a set, you can use either the remove(), discard() and the pop() functions.

The remove() function takes one parameter which is the item to be removed from the set.

Example:

My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.remove(2)
print(My_Set)

Output: {1, 4.6, 7.8, ‘r’, ‘s’}

As you can see, 2 has been removed from the set using the remove() function. In case you specify some element as a parameter to remove() that does not exist in the set, it will throw an error.

Now, if you want to remove some element from the set, and if you are not sure whether that element is actually present in the set or not, you can use the discard() function. This function will take the element to be removed from the set as a parameter but in case the element is not present, it does not throw an error.

Example:

My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.discard(4.6)
My_Set.discard('i')
print(My_Set)

Output: {1, 2, 7.8, ‘r’, ‘s’}

The above output shows that 4.6 has been removed from My_Set but discard() has not thrown an error when I used My_Set.discard(‘i’) even though ‘i’ is not present in my set.

The pop() function also removes set elements, but since a set is unordered, you will not know which element has been removed.

Example:

My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.pop()
print(My_Set)

Output: {2, 4.6, 7.8, ‘r’, ‘s’}

The output shows that, using pop() some random element has been removed, which in this case is 1.

Now, in case you want to delete all elements present in a set, you can use the clear() method.

Example:

My_Set={1, 2, 4.6, 7.8, 'r', 's'}
My_Set.clear()
print(My_Set)

Output: set()

As you can see in the above output, My_Set is an empty set.

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

Example:

My_Set={1, 2, 4.6, 7.8, 'r', 's'}
del My_Set
print(My_Set)

When you run the above code, it will throw an error because My_Set is deleted.

You can also perform the various mathematical operations on a set such as union, intersection, difference, etc which is discussed below.

 

Union of Sets

Union of sets refers to the concatenation of two or more sets into a single set by adding all unique elements present in both sets. This can be done in two ways:

  • Using pipeline
  • Using union() function

 

Using pipeline symbol:

Two sets can be concatenated using the | symbol as follows:

 

Example:


a={1, 2, 4.6, 7.8, 'r', 's'}
b={2,5,'d','abc'}
c=a|b
print(a|b)

Output:{1, 2, 4.6, 5, 7.8, ‘r’, ‘abc’, ‘s’, ‘d’}

As you can see, in the above output, a union of set a and set b is stored in a new set c. You can concatenate more than two sets as well using | symbol.

Example:

a={1, 2, 4.6, 7.8, 'r', 's'}
b={2,5,'d','abc'}
c={2,3,4,5}
d=a|b|c
print(d)

Output:

{1, 2, 3, 4, 4.6, 5, 7.8, 'abc', 'd', 'r', 's'}

Using the union() method:

To concatenate two or more sets, you can use the union() method as follows:

Example:

a={1, 2, 4.6, 7.8, 'r', 's'}
b={2,5,'d','abc'}
c={'m',23,76,4.7}
print("Set a U b = ",a.union(b))
print("Set a U b U c = ",a.union(b,c))

Output:

Set a U b = {1, 2, 4.6, 5, 7.8, ‘r’, ‘abc’, ‘s’, ‘d’}

Set a U b U c = {1, 2, 4.6, 5, 4.7, 7.8, ‘r’, 76, 23, ‘abc’, ‘m’, ‘s’, ‘d’}

The above output shows that the d is a union of sets a, b and c.

 Intersection of Sets

The intersection of two or more sets is a new set consisting of only the common elements present in those sets.

This can be done in two ways:

  • Using ‘&’ symbol
  • Using intersection() function

Using ‘&’ symbol:

You can determine the intersection of two or more sets using the ‘&’ symbol as follows:

Example:

a={1, 2,5, 4.6, 7.8, 'r', 's'}
b={2,5,'d','abc'}
c={2,3,4,}
print(a&b)
print(a&b&c)

Output:

{2, 5}
{2}

The above output shows the union of sets a,b and c.

Using intersection() function:

You can determine the intersection of two or more sets using the intersection() function as follows:

Example:

a={1, 2,5, 4.6, 7.8, 'r', 's'}
b={2,5,'d','abc'}
c={2,3,4}
print("Set a intersection b = ",a.intersection(b))
print("Set a intersection b intersection c = ",a.intersection(b,c))

Output:

Set a intersection b = {2, 5}

Set a intersection b intersection c = {2}

The above output shows the intersection of sets a, b and c.

Difference of Sets:

The difference of sets produces a new set consisting of elements that are present only in one of those sets. This means that all elements except the common elements of those sets will be returned.

This can be done in two ways:

  • Using the ‘-‘ symbol
  • Using difference() function

Using the ‘-‘ symbol:

To find the difference of two sets using ‘-‘ symbol, you can do as follows:

Example:

a={1, 2,5, 4.6, 7.8, 'r', 's'}
b={2,5,'d','abc'}
c={2,3,4}
print(a-b-c)

Output: {1, 4.6, 7.8, ‘r’, ‘s’}

The output consists of all elements of set ‘a’ except those that are present in ‘b’ and ‘c’.

Using the difference() function:

The difference of sets can be determined using the built-in difference() function as follows:

Example:

a={1, 2,5, 4.6, 7.8, 'r', 's'}
b={2,5,'d','abc'}
c={2,3,4}
print("Set a - b = ",a.difference(b))
print("Set a - b - c = ",a.difference(b,c))

Output:

Set a – b = {1, 4.6, 7.8, ‘r’, ‘s’}

Set a – b – c = {1, 4.6, 7.8, ‘r’, ‘s’}

The above output is the result for difference using the difference() function.

Now what if you do not want to change the elements of your set at all, you can make use of frozen sets which is discussed below.

What is a frozen set?

A frozen set in Python is a set whose values cannot be modified. This means that it is immutable unlike a normal set which I have discussed previously. Frozen sets help serve as a key in dictionary key-value pairs.

How to create frozen sets?

Frozen sets can be obtained using the frozenset() method. This function takes any iterable items and converts it to immutable.

Example:

a={1, 2,5, 4.6, 7.8, 'r', 's'}
b=frozenset(a)
print(b)

Output: frozenset({1, 2, 4.6, 5, 7.8, ‘r’, ‘s’})

The above output consists of set b which is a frozen version of set a.

Accessing Elements of a Frozen Set

Elements of a frozen set can be accessed by looping through it as follows:

Example:

b=frozenset([1, 2, 4.6, 5, 7.8, 'r', 's'])
for x in b:
print(x)

Output:

1
2
4.6
5
7.8
s

The above output shows that using the for loop, all elements of the frozen set b have been returned one after the other.
Frozen sets are immutable, therefore, you cannot perform operations such as add(), remove(), update(), etc.
Hope you are clear with all that has been shared with you in this tutorial. This brings us to the end of our article on Sets in Python. Make sure you practice as much as possible and revert your experience. 

Got a question for us? Please mention it in the comments section of this “Sets in Python” blog and we will get back to you as soon as possible.

To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access. 

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 23rd March,2024

23rd March

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 20th April,2024

20th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What are Sets in Python and How to use them?

edureka.co