Using a set in python

problem

You’re learning Python and you wish to use a Set data structure. A set in programming origins from the mathematical notion of a set. This means, they’re only distinct values, no duplicates.

SOLUTION

Python comes with a built-in Set data structure. In order to use it we need to initialize,

for example in a local variable:

From a list
using_sets.py
				
					colors = set(['blue', 'green', 'red', 'gray']) # convert from list

				
			

The code above creates a set with 4 colors. The values are sourced from a list. 

From a tuple
using_sets.py
				
					fruits = set(('apple', 'kiwi', 'pineapple')) # convert from tuple
				
			

This case we created a set from a tuple.

The set() can take an iterable collection and convert it to a set, for example a list or tuple.

From a list containing duplicates

If we have a list with duplicates and convert it to a set, the duplicates are dropped.

For example:

using_sets.py
				
					duplicates = ['sky','beach','building','sky','beach']
items = set(duplicates)
print(items)
				
			
output
unique items in set Python

As you can see the duplicated values have been discarded.

Adding a new item

We can insert a new item using add()

using_sets.py
				
					colors.add('yellow')
print(colors)
				
			
output
add item in set Python

It’s adding it at the end of the set.

Removing an item (the last)

Using pop(), for example:

using_sets.py
				
					colors = set(['blue', 'green', 'red', 'gray'])
first_color = colors.pop()
print(first_color) # gray
				
			

It will remove the last item from the set. In this case “gray”. The set now contains the following values.

output
set pop in Python
Removing a specific item

We can do that by using remove(), we need to provide the item we wish to remove. For example, to remove “blue”

using_sets.py
				
					colors.remove(“blue”) #it will search for it and if found will remove it
				
			

If it’s not found, it will throw a KeyError.

Note: remove() does not return the item, pop() does.

Removing using discard()

The same like the remove() above, just it doesn’t throw an error in case the item is not in the set.

Removing all items
using_sets.py
				
					colors.clear()
				
			

This clears all the contents of the set.

Merging two sets

Let’s say I want to create one set that is made of colors and fruits sets above.

using_sets.py
				
					colors = set(['blue', 'green', 'red', 'gray']) # create a set from a list
fruits = set(('apple', 'kiwi', 'pineapple')) # create a set from a tuple
new_set = colors.union(fruits) # merge the two sets into one
print(new_set)

				
			
output
union set in Python
Finding the intersection of two sets

To find the common items between two sets, we can use intersection()

using_sets.py
				
					nums = set([1,2,3,4,5,6,7,8,9,10])
even = set([0,2,4,6,8,10])
common = nums.intersection(even)

print(common)
				
			
output
common items of two sets
Finding the intersection of two sets
using_sets.py
				
					nums = set([1,2,3,4,5,6,7,8,9,10])
even = set([0,2,4,6,8,10])
difference = nums.difference(even)

print(difference)

				
			
output
set.difference() in python

It returns the opposite of intersection, how two sets differ.

Checking if a set is a subset of another

You can check if a set is a subset of another by using the issubset() function. For example:

using_sets.py
				
					odds = set([1,3,5])
nums  =set ([1,2,3,4,5,6,7,8,9,10])
is_subset = odds.issubset(nums)

print(is_subset)

				
			
output
set.is_subset()

conclusion

In this post we saw how to initialize a Set from a list and from a tuple. A set contains only unique values by definition. Also, a set has ready functions on it that can be very useful for example finding the union, intersection, difference between two sets.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x