Sets in Python

Introduction

Set is an unordered collection of elements with no duplicates. They can only contain immutable objects, therefore sets can’t contain list, dictionaries or another sets. Sets are usually used when someone needs to know whether a particular element is in a collection or not and the order itself does not matter.

The good use case is, for example, having a set of spoken languages for a call center operator. It can contain several languages or only one language. Order of the languages doesn’t matter, because the operator either speaks that language or not. Duplicate items would also have no sense in such a scenario.

Now, that we know what sets are for, let’s look at some practical examples using Python 3 shell.

How to create a Set?

The first way to create a set is just define a sequence of immutable objects in a curly braces:

>>> numbers = {1, 2, 3, 4, 5, 6, 7, 8}

Another option is to create a set from a list. The built-in set() function will do this for us. Of course, the resulted set will have duplicates removed:

>>> numbers =  set([5, 10, 10, 15])
>>> type(numbers)
<class 'set'>
>>> numbers
{10, 5, 15}

Set operations

Besides other collection related operations, like len() or in, sets have their own operators. Two most popular set operations are adding and removing set elements. For these tasks set objects have add() and remove() methods. Let’s have a look at the example:

>>> languages = {'Spanish', 'Russian', 'English'}
>>> languages.add('German')
>>> languages
{'Russian', 'English', 'Spanish', 'German'}
>>> languages.remove('Spanish')
>>> languages
{'Russian', 'English', 'German'}

Unions and Intersections and Differences

There are three operations which are specific to sets:

  • union – operator “|”. The result set will contain all the elements from both sets with duplicates removed.
  • intersection – operator “&”. The result set will contain only elements which belong to both sets.
  • difference – operator “^”. The result set will contain only elements found only in one set or the other, but not both.
>>> numbers = {1, 2, 3, 4, 5, 6, 7, 8}
>>> primes = {2, 3, 5, 7, 11, 13}
>>> >>> numbers | primes #union {1, 2, 3, 4, 5, 6, 7, 8, 11, 13} >>> numbers & primes #intersection {2, 3, 5, 7} >>> numbers ^ primes #difference {1, 4, 6, 8, 11, 13}

Tags:

Add a Comment