Python

Python Sets Tutorial

In this article, we will learn how to use Sets in Python.

1. Introduction

Python is an easy-to-learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications.

2. Python Set

Sets are used to store multiple items in a single variable. Python set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection that is unordered (items do not have a defined order), unchangeableunindexed and they do not allow duplicate values. Sets are written with curly brackets.

>>> mySet = {"one", "two", "three"}
>>> print(mySet)
{'three', 'one', 'two'}

Set items can appear in a different order every time you use them, and cannot be referred to by index or key. Sets are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can add new items. Sets cannot have two items with the same value:

>>> mySet = {"one", "two", "three", "one"}
>>> print(mySet)
{'three', 'one', 'two'}

3. Python Set Methods

Most, though not quite all, set operations in Python can be performed in two different ways: by operator or by method. To get the number of items in the set use the len() method:

{'three', 'one', 'two'}
>>> print(len(mySet))
3

The items in the set can be of type String, Integer, or boolean. A set can also contain items of different types:

>>> set1={True, "String", 112}
>>> print(set1)
{112, True, 'String'}

We can also use a set() constructor to make a set:

>>> newset = set(("London", "New York", "India"))
>>> print(newset)
{'New York', 'London', 'India'}

We can use the in operator to find if an element is in the set or not:

>>> mySet = {'one', 'two', 'three'}
>>> 'two' in mySet
True
>>> '1' in mySet
False

We can use the union (|) operator to get all the elements in the sets combined. The set union can also be obtained with the .union() method. The method is invoked on one of the sets, and the other is passed as an argument:

>>> s1={'This', 'is', 'an'}
>>> s2={'example', 'of'}
>>> s3={'Java Code Geeks'}
>>> s1 | s2 | s3
{'This', 'example', 'of', 'Java Code Geeks', 'is', 'an'}
>>> s1.union(s2,s3)
{'This', 'example', 'of', 'is', 'an'}

The operator and method behave identically but there is a subtle difference between them. When you use the | operator, both operands must be set. The .union() method, on the other hand, will take any iterable as an argument, convert it to a set, and then perform the union.

We use the intersection() method to find the common elements of the sets:

>>> s1 = {1, 2, 3}
>>> s2 = {3, 4, 5}
>>> s1.intersection(s2)
{3}

You can specify multiple sets with the intersection method and operator, just like you can with set union:

>>> s1 = {1, 2, 3, 4}
>>> s2 = {2, 3, 4, 5}
>>> s3 = {3, 4, 5, 6}
>>> s1.intersection(s2,s3)
{3, 4}
>>> s1 & s2 & s3
{3, 4}

4. Loop items

In this section we will see how we can loop items in a python set. You cannot access items in a set by referring to an index, since sets are unordered the items has no index.

4.1 for loop

One way to loop the items in a set is via a for loop.

>>> mySet = {'This', 'is', 'a', 'looping', 'example'}
>>> for x in mySet:
...   print(x)
...
looping
a
This
example
is
>>>

4.2 enumerating over Python set

Another way of looping through the set elements is by enumerating over them. When we use enumerate() method, we receive a counter along with the iterable item.

>>> mySet = {'This', 'is', 'a', 'looping', 'example'}
>>> for i, element in enumerate(mySet):
...   print(element)
...
looping
a
This
example
is
>>>

4.3 iter()

We can use the iter() method as well for iterating through a python set. The iter() method will return an iterator. Using that iterator, we can iterate over a given object

>>> mySet = {'This', 'is', 'a', 'looping', 'example'}
>>> for element in iter(mySet):
...   print(element)
...
looping
a
This
example
is
>>>

5. Summary

In this article, we learned about Sets in Python. We looked at different ways of constructing Set objects and also some of the common methods which we can use for Sets. We also looked at some of the most commonly used operators for sets. In the end we also looked at different ways of looping through the elements of the sets.

Last updated on Apr. 13th, 2022

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button