Python Set

Before we dive into the topic of Python Set, let’s take some time to find the answer for the below question:

There is a list l=[1,4,7,4,2,7,2,3,3]. Your job is to return the list without any duplicates.

Solution to Find Unique elements

l=[1,4,7,4,2,7,2,3,3]
output=[]
for i in l:
  if i not in output:
    output.append(i)
print(output)

There is another easy way to do this. Convert the list to set using the set() constructor and check the output.

l=[1,4,7,4,2,7,2,3,3]
print(set(l))

The order of the elements might be different but the solution is correct.

What is Python set?

A Python Set is an unordered collection data type that is iterable, mutable, unordered, unindexed and has no duplicate elements. In Python, sets are written with curly brackets.

Accessing elements from Python Set

Since the sets the unordered, the item has no index. We can access the elements of the set by using the for loop.

s={'a','b','c'}
for i in s:
   print(i)

Keep executing the above code and you can observe that every time the order in which the elements are printed is different. That’s why we call sets are unordered.

Changing Python set elements

add()

add() method is to add elements to the set

update()

To add more than one element to the set, update() is used

union()

Adds a set to another and returns a new set containing all items from both sets.

Python Set – Add, Update, Union

s={'a','b','c'}

# add
s.add(1)
print(s)

# update
s.update({2,3,4})
s.update(['e','f'])
print(s)

# union
s={1,2,3}
s1=s.union(['a','b','c'])
print(s1)

Python Set – Removing elements

pop()

Removes the last element from the set. Since sets are unordered, we don’t know, what item it removes.

remove()

To remove a specific element from the set, remove() method is used. It raises an error if the specified element is not present in the set.

discard()

Similar to remove(), discard() removes the specifies element from the set. But discard() does not raise an error if the element is not present.

clear()

clear() empties the set.

del

The del keyword deletes the set

Code for Set Remove Operations

s={1, 2, 3, 4, 'e', 'c', 'a', 'b', 'f'}

# pop
s.pop()
print(s)

# remove
s.remove('e')
print(s)

# discard
s.discard('e')
print(s)

# del
del s
s={1, 2, 3, 4, 'e', 'c', 'a', 'b', 'f'}

# clear
s.clear()
print(s)

Other commonly used operations on Set

len()

len() method is used to find the length of a set

in operator

To check if a specific item exists in a set.

Code for len() and in Operator

s={1,2,3,'a','b','c'}

#len
print(len(s))

#in operator
print('d' in s)
print('a' in s)

Reference Python Tutorial

Translate »