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
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.