Python Set – A complete guide with Examples

In this Python article, we will discuss the Set data type, how to create, update and access it along with various other operations and examples.

1. What is Set datatype?

In python, Set is an unordered collection of data that is mutable as well as iterable. By default, Set does not contain any duplicate value. There is no particular order of elements in a set i.e. we can not guarantee the order of elements while iterating it. Also, we can not access elements via index.

The main reason for using a set over a list is its optimized search for a mentioned value in the set and when we want to ensure that every element is only once and duplicate is present.

Read more: Lists in Python

Now, we will go through different operations on a set in detail.


2. How to create a Set?

set() function is used to create a set with elements placed inside the curly brackets {} and separated by comma(,).

Let’s take an example to understand the implementation.

# Creating a Set
set_value = set("codingeek.com")
print("\nThe Set contains: ")
print(set_value)

# Creating a Set using variable
str = 'Teamspirit'
set_value = set(str)
print("\nThe Set contains: ")
print(set_value)

# Creating a Set using a List
set1_value = set(["Best", "Learning", "Platform"])
print("\nSet with the use of List: ")
print(set_value)
Output
The Set contains: 
{'i', 'g', 'm', 'c', 'k', 'n', '.', 'd', 'e', 'o'}

The Set contains: 
{'i', 'm', 'p', 'T', 'r', 'a', 't', 's', 'e'}

Set with the use of List: 
{'i', 'm', 'p', 'T', 'r', 'a', 't', 's', 'e'}

As already discussed, the set contains only unique elements, but during set creation, we can pass multiple duplicate values but the set will include it only once.

The order of elements in a set is not defined and is not changeable. We can pass multiple data type values to the set.

# Set with duplicate values
set_value = set([1, 2, 4, 4, 3, 3, 3, 6, 5])
print("\nSet contains: ")
print(set_value)
  
# Set with mixed type of values
set_value = set([8, 7, 'python', 3, 'For', 1, 'learners'])
print("\nSet contains: ")
print(set_value)
Output
Set contains: 
{1, 2, 3, 4, 5, 6}

Set contains: 
{1, 3, 7, 8, 'For', 'python', 'learners'}

3. How to add elements in a Set?

There are few ways to add elements to a set. Let’s discuss them one by one with suitable examples.

3.1. add() – add an element to a Set

We can add elements to a set with the help of a built-in function add(). At a time, we can only add one element to the set with the add() method. However, we may use loops to add multiple elements at a time.

Note:  We cannot add a list as an element to a set as they are not hashable but we can add a tuple as tuples are immutable so they are hashable.

# Adding element to the Set
set_value = set()
set_value.add(8)
set_value.add(9)
print("\nSet contains: ")
print(set_value)

# Adding tuple to the set
set_value.add((1, 7))
print("\nSet contains: ")
print(set_value)

# Adding elements using Iterator
for i in range(0, 10):
  set_value.add(i)
print("\nSet finally contains: ")
print(set_value)
Output
Set contains: 
{8, 9}

Set contains: 
{8, 9, (1, 7)}

Set finally contains: 
{0, 1, 2, 3, (6, 7), 4, 5, 6, 8, 9, 7}

3.2. update() – add an element to a Set

We can use update() to add multiple elements to the set. It accepts various things like a list, a string, a tuple, another set as arguments. But it still avoids duplicate elements.

# using Update()
set_value = set([ 6, 9, (4, 5)])

# uplicate 6,9 willl be reemoved
set_value.update([1, 13, 6, 9])
print("\nSet contains: ")
print(set_value)
Output
Set contains: 
{1, 6, 9, 13, (4, 5)}

4. How to access elements in a Set – Iteration and Membership Test

Generally, we cannot access the set items by simple index referring because the sets are unordered so the items contained in the set have no particular index.

But to access the set, we can loop through the set using a for loop.

We can specifically search for a value in a set, by using the in keyword, which is also known as the membership test of an element.

Let’s consider an example to access elements via iterating a Set and do a membership test in a set.

set_value = set(["Apple", "Orange", "Mango", "Grape"])

print("Elements contained in the set are: ")

for i in set_value:
  print(i, end=" ")
print("\n")

# membership test
print("Mango" in set_value)
Output
Elements contained in the set are: 
Apple Orange Mango Grape 

True

5. How can we remove elements from a Set?

There are multiple ways by which we can remove elements in a Set in Python. Let’s see one by one with small examples.

5.1. Using remove() – delete element in a Set

We can remove elements from any set by using built-in function remove(). If we try to remove an element that does not exists in the Set then it will throw an error. 

Let’s implement some examples to delete elements from a Set using remove() method.

set_value = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# using Remove() method
set_value.remove(5)
set_value.remove(6)
print("\nSet contains(after removing): ")
print(set_value)

# using iterator method to remove element
for i in range(2, 8):
  set_value.remove(i)
    
print("\nSet contains(after removing): ")
print(set_value)
Output
Set contains(after removing): 
{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}
Traceback (most recent call last):
  File "C:/Users/ASUS/Documents/setfake.py", line 11, in 
    set_value.remove(i)
KeyError: 5

We faced an error in the above program due to prior deletion of element 5

5.2. Using discard() – delete element in a Set

As we saw above in the remove() method that the deleting of a nonexisting element gives KeyError but sometimes we do not want to do the membership test before removing the element.

To solve that issue, we can use discard() method to remove elements from a given set without KeyError. If it doesn’t find the element in the set, it will remain unchanged.

set_value = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# using discard() method
set_value.discard(4)
set_value.discard(10)
# no error on discarding a non existing value
set_value.discard(10)
print("\nSet contains(after discarding: ")
print(set_value)
  
Output
Set contains(after discarding: 
{1, 2, 3, 5, 6, 7, 8, 9, 11, 12}

5.3. Using clear() – delete all elements of a Set

If we want to remove all elements from the set, we can use the clear() function. It will leave an empty Set at the end.

set_value = set([1, 5, 7, 11, 15])

# Removing the elements using clear()
set_value.clear()

print("\nSet contains: ", set_value)
Output
Set contains: set()

5.4. Using pop() – delete element first element of the Set

As the name suggests, the pop() function removes only the first element of the set. It can also remove the element and return it from the set.

set_value = set([1, 2, 3, 4, 5])

# Removing element using pop()
print("Popped value - ", set_value.pop())
print("Remaining values : ", set_value)
Output
Popped value -  1
Remaining values :  {2, 3, 4, 5}

6. What is the use of the Frozen set in python

The Frozenset is a class similar to the Set class but the main difference is that elements of the frozen set remain the same after creation and cannot be changed like in the case of a normal set.

Frozen sets are immutable objects and any operation performed on these sets does not change the values. Since the frozen sets are immutable objects it does not contains the methods to add, update or delete the elements.

Frozen sets are hashable and hence they can be used as keys in Python dictionary whereas normal Sets are unhashable and hence cannot be used as keys for the dictionary.

If we pass no parameters, it returns an empty frozen set. Frozen sets contains methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union().

Let’s take a small example.

tup = ('L', 'e', 'a', 'r', 'n', 'e', 'r', 's')

fSet1 = frozenset(tup)
print("FrozenSet contains: ", fSet1)

# No parameter is passed

fSet2 = frozenset()
print("\nFrozenSet contains: ", fSet2)

print("Is disjoint - ", fSet1.isdisjoint(fSet2))
print("Difference - ", fSet1.difference(fSet2))
Output
FrozenSet contains:  frozenset({'a', 's', 'L', 'n', 'r', 'e'})
FrozenSet contains:  frozenset()
Is disjoint -  True
Difference -  frozenset({'n', 'a', 's', 'L', 'e', 'r'})

7. Important Built-in functions for a Set

Given below is the list of some in-built functions that can be applied to a set. Arranged in alphabetical order.

In-Built FunctionSpecification
add()Adds an element to a set
clear()Removes all elements from a set
copy()Returns a shallow copy of a set
difference()Returns the difference of two or more sets as a new set
difference_update()Removes all elements of another set from this set
discard()Removes an element from set if it is a member. (Do nothing if the element is not in set)
intersection()Returns the intersection of two sets as a new set
intersection_update()Updates the set with the intersection of itself and another
isdisjoint()Returns True if two sets have a null intersection
issubset()Returns True if another set contains this set
issuperset()Returns True if this set contains another set
pop()Removes and returns an arbitrary set element. Raise KeyError if the set is empty
remove()Removes an element from a set. If the element is not present in the set, raise a KeyError
symmetric_difference()Returns the symmetric difference of two sets as a new set
symmetric_difference_update()Updates a set with the symmetric difference of itself and another
update()Updates a set with the union of itself and others
union()Returns the union of sets in a new set
Methods applicable in Set in Python

8. Conclusion

In this article, we covered every detail of the set datatype.

  • What is the set datatype?
  • How to create a set.
  • How to add an element to set with two different methods.
  • How can we access a set?
  • How to remove elements from a set using four different techniques along with examples for each.
  • What is the use of Frozenset in python?

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x