Skip to content

Python Set – An Intro for Beginners

Python Set

Python Set is used to store multiple items in a single variable . Python Set is surrounded by curly braces ({}) . Python provides total 4 built-in data types to store collection of data of which one is Set . The other data types are List , Dictionary and Tuple .

How to create a Set in Python ?

There are multiple ways to create a Python Set –

To check if it is a set or not we can use type() function .

# Creating a set in Python

# Using curly braces ({})
set_from_bracket = {"Rajkumar","apple",True,2.5,10}
print(set_from_bracket)
# checking the type
print("type of set_from_bracket",type(set_from_bracket))

# using set() function
set_from_function = set(("Rajkumar","apple",True,2.5,10))
print(set_from_function)
# checking the type
print("type of set_from_function",type(set_from_function))

# using set comprehension
set_from_comprehension  = {item for item in range(5)}
print(set_from_comprehension)
# checking the type
print("type of set_from_comprehension",type(set_from_comprehension))
{True, 2.5, 'Rajkumar', 'apple', 10}
type of set_from_bracket <class 'set'>
{True, 2.5, 'Rajkumar', 'apple', 10}
type of set_from_function <class 'set'>
{0, 1, 2, 3, 4}
type of set_from_comprehension <class 'set'>
  • In the above code we have created set using various ways
  • First we have created set using curly braces ({}) . Then we have printed the set and also its type .
  • Second we have created set using set() . Then we have printed the set and also its type .
  • Third we have created set using set comprehension . Then we have printed the set and also its type .
  • From the output we can see that in every case type is set .

Note :

Set items are separated by comma (,) and it can be of any type(Except list ,set and dictionary) as we have seen in the previous code .

Characteristics of a Set in Python

Python set is unindexed , unordered and immutable(unchangeable) collection of items . Set does not allow duplicate values .

Python Set is unindexed

Python set is unindexed it means we can not access set items using its index . If we try to do that it will raise TypeError .

Example 1:

# creating a set
myset = {"Rajkumar","apple",True,2.5,10}

# Trying to access 2nd time using its index
print(myset[1])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_9616/2301275578.py in <module>
      3 
      4 # Trying to access 2nd time using its index
----> 5 print(myset[1])

TypeError: 'set' object is not subscriptable

In the above code when we have tried to access set items using its index it has raised TypeError .

Python Set is unordered

Python Set items are unordered it means that it does not maintain a defined order .

Example 1:

# creating a set
myset = {"Rajkumar","apple",True,2.5,10}

# printing the set
print(myset)
{True, 2.5, 'Rajkumar', 'apple', 10}

In the above code , from output we have seen that the set did not maintain its order as defined while creating it .

Python Set is mutable | How to update a Set in Python ?

Python set is mutable but set items are immutable it means we can not change set items but we can delete and add items in the set .

# creating a set
myset = {"Rajkumar","apple",True,2.5,10}

# adding an element in the set
myset.add(3)

# printing the updated set
print(myset)
{True, 2.5, 3, 'Rajkumar', 'apple', 10}
  • In the above code first we have created a set named myset as {"Rajkumar","apple",True,2.5,10}
  • Then we have used add() method to add 3 in the set .
  • After that we have printed the set . As set is unordered so 3 is added at a random place inside the set .

Python Set does not allow duplicate values

Python set does not allow duplicate values . If we create a set with duplicate values then it will only accept one value .

Example 1:

# creating a set with duplicate values
myset = {"Rajkumar","apple",True,2.5,10,10,True}

# printing the set
print(myset)
{True, 2.5, 'Rajkumar', 'apple', 10}

In the above code when we have created the set , the set contains 2 nos True and 2 nos 10 . But when we have printed the set it contains only 1 no True and 1 no 10 .

How to delete a Set in Python ?

We can delete a set in Python using del keyword . But if we want to access the set after deleting it using del keyword it will raise a NameError .

Example 1:

# creating a set
myset = {"Rajkumar","apple",True,2.5,10}

# deleting the set
del myset

# printing the deleted set
print(myset)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_9616/2084833656.py in <module>
      6 
      7 # printing the deleted set
----> 8 print(myset)

NameError: name 'myset' is not defined

Iterating a Set in Python

We can iterate a set in Python using for-loop and while-loop .

Example 1: How to access elements of set in Python ?

We can access elements of set in Python using for-loop .

# creating a set
myset = {"Rajkumar","apple",True,2.5,10}

# iterating using for loop
for item in myset:
    print(item)
True
2.5
Rajkumar
apple
10

In the above code we have accessed elements of the set using for loop and printed all the elements .

Example 2:

# creating a set
myset = {"Rajkumar","apple",True,2.5,10}

# iterating using while loop
i=0
while i<len(myset):
    print(list(myset)[i])
    i+=1
True
2.5
Rajkumar
apple
10

In the above code we have iterated set elements using while-loop . As set is unindexed so we have converted it to a list using list() function .

To know about len() function click here .

Nested Set in Python

When we use set inside a set then it is called Nested set . As we set items can`t be a set so we will use frozenset as set item .

Example :

# nested set in python
myset={"Rajkumar","apple",True,2.5,10,frozenset((2,3))}
print(myset)
{True, 2.5, 'Rajkumar', frozenset({2, 3}), 'apple', 10}

In the above code we have seen that Python accepts a frozenset as set item .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply