Python is undoubtedly one of the most popular languages today, and in this article, you will learn everything about set in python with the help of examples. We’ll cover topics like creating sets, modifying sets, their methods, and more.

What Is a Set?

Set is a data type in python used to store several items in a single variable. It is one of the four built-in data types (List, Dictionary, Tuple, and Set) having qualities and usage different from the other three. It is a collection that is written with curly brackets and is both unindexed and unordered. 

A set is mutable, i.e., we can remove or add elements to it. Set in python is similar to mathematical sets, and operations like intersection, union, symmetric difference, and more can be applied. 

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

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. 

After a set is created, its items cannot be changed. However, new items can be added. As we mentioned, all set items need to be unique because duplicates are not allowed. Items in a set can be of any data type.

Set items can be of any data type: String, Boolean, tuple, float, int. 

set1 = {"ab", "bc", "cd"}

set2 = {11, 15, 17, 19, 13}

set3 = {False, False, True}

How to Create a Set in Python

To create a python set, place all elements or items separated by a comma inside curly braces {}. The built-in set() function can also be used to create a set in python. As per definition, a set can have any number and any items. However, mutable elements such as dictionaries, lists, or sets are not allowed as its elements. 

# creating different types of sets

# Integer set

integer = {11, 12, 23}

print(integer)

# Mixed set

mixed = {10.0, "Hi", (11, 12, 13)}

print(mixed)

Output: (Notice the random order)

SetinPython

More examples:

# set with duplicates

dup = {11, 12, 13, 14, 13, 12}

print(dup)

# set made from a list

lis = set([11, 12, 13, 2])

print(lis)

Output:

SetinPython_2.

How to Modify a Set in Python

Sets, though mutable, are unordered. Thus, there is no scope for indexing. Indexing or slicing cannot change or access an item of a set as a python set does not support it. 

We use the add() method to add a single element and update() method when multiple elements are to be added. The elements can be of the form lists, tuples, strings, or sets in the update() method. Duplicates are avoided in all cases. 

# initializing a set

a = {11, 13}

print(a)

# adding an item

a.add(12)

print(a)

# adding multiple elements

a.update([22, 13, 14])

print(a)

# adding list and set

a.update([14, 15], {11, 16, 18})

print(a)

Output:

SetinPython_3

How to Get the Length of a Set

The len() method is used to determine the number of items a set has. For example:

cars = {"Audi", "BMW", "Chevrolet"}

print(len(cars))

Output:

SetinPython_4

Various Set Methods (With Their Uses)

Set in python have various methods. We have seen the use of some of the above. Below is a list of all the available methods for the set objects:

  1. update()- used to update the set with union of others and itself
  2. add()- used to add a single item to the set
  3. copy()- used to return a copy of the set
  4. clear()- used to remove all items of the set
  5. discard()- used to remove an item from the set. If the item is not an element, then nothing is done
  6. union()- used to return a new set as a union of sets
  7. difference()- used to return a new set as the difference of two or more sets
  8. difference_update()- used to remove intersecting items from this set
  9. intersection()- used to return a new set as intersection of two sets
  10. intersection_update()- used to update a set with the intersection of another set and itself
  11. pop()- used to return and remove an arbitrary set item, KeyError is raised if the set is empty
  12. remove()- used to remove an item from the set. KeyError is raised if an item is not a member of the set
  13. issubset()- if another set is contained in this set, return true
  14. issuperset()- if this set is contained in another set, return true
  15. isdisjoint()- if the intersection of two sets is null, return true
  16. symmetric_difference- used to return a new set as the symmetric difference of two sets 
  17. symmetric_difference_update()- used to update a set with the symmetric difference of another set and itself 

Example of various methods:

x = {"pear", "grapes", "kiwi"} 

x.add("orange")

print(x)

y = {"mango", "banana", "apple"}

x.update(y)

print(x)

x = y.copy()

print(x)

x.clear()

print(x)

y.discard("banana")

print(y)

z = x.union(y)

print(z)

z = x.difference(y)

print(z)

Output: 

SetinPython_5

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Set() Constructor in Python

As mentioned earlier, in-built set() constructor can also be used to create a set in python. Here’s how:

cars = set(("Audi", "BMW", "Chevrolet")) # double round-brackets are used

print(cars)

Output:

SetinPython_6

Python Frozenset

A new class having the characteristics of a set in python whose items cannot be changes post assignment is known as Frozenset. Like tuples behave as immutable lists, frozensets behave as immutable sets. 

As sets are unhashable, they cannot be uses as keys of a dictionary. However, frozensets are hashable and can act as keys of a dictionary. 

frozenset() function is used to create frozensets. As they are immutable, add and remove item methide aren’t supported. However, the following methods are:

cop(), intersection(), union(), difference(), issubset(), issuperset(), isdisjoint() and symmetric_difference().

Here’s an example:

#initialize frozenset a and b

a = frozenset([11, 12, 13, 14])

b = frozenset([23, 24, 25, 26])

print(a.isdisjoint(b))

print(a.difference(b))

print(a|b)

Output:

SetinPython_7

As seen above, set in python is an unindexed and unordered collection having unique members. It is necessary to understand the attributes of a collection type before using it. This can increase the security and efficiency of your program. 

You can master Python with our Python Training, and accelerate your development or data science career, starting now! And in case you have any questions or doubts about ‘set in python, you can write it down in the comments section below and our experts will help you out.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 18 Dec, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449