Python Set

Summary: in this tutorial, you’ll learn about Python Set type and how to use it effectively.

Introduction to the Python Set type

A Python set is an unordered list of immutable elements. It means:

  • Elements in a set are unordered.
  • Elements in a set are unique. A set doesn’t allow duplicate elements.
  • Elements in a set cannot be changed. For example, they can be numbers, strings, and tuples, but cannot be lists or dictionaries.

To define a set in Python, you use the curly brace {}. For example:

skills = {'Python programming','Databases', 'Software design'}Code language: JavaScript (javascript)

Note a dictionary also uses curly braces, but its elements are key-value pairs.

To define an empty set, you cannot use the curly braces like this:

empty_set = {}

…because it defines an empty dictionary.

Therefore, you need to use the built-in set() function:

empty_set  = set()Code language: JavaScript (javascript)

An empty set evaluates to False in Boolean context. For example:

skills = set()

if not skills:
    print('Empty sets are falsy')
Code language: PHP (php)

Output:

Empty sets are falsy    Code language: PHP (php)

In fact, you can pass an iterable to the set() function to create a set. For example, you can pass a list, which is an iterable, to the set() function like this:

skills = set(['Problem solving','Critical Thinking'])
print(skills)Code language: PHP (php)

Output:

{'Critical Thinking', 'Problem solving'}Code language: JavaScript (javascript)

Note that the original order of elements may not be preserved.

If an iterable has duplicate elements, the set() function will remove them. For example:

characters = set('letter')
print(characters)Code language: PHP (php)

Output:

{'r', 'l', 't', 'e'}
Code language: JavaScript (javascript)

In this example, the string 'letter' has two e and t characters and the set() removes each of them.

Getting sizes of a set

To get the number of elements in a set, you use the built-in len() function.

len(set)
Code language: JavaScript (javascript)

For example:

ratings = {1, 2, 3, 4, 5}
size = len(ratings)

print(size)    Code language: PHP (php)

Output:

5

Checking if an element is in a set

To check if a set contains an element, you use the in operator:

element in setCode language: JavaScript (javascript)

The in operator returns True if the set contains the element. Otherwise, it returns False. For example:

ratings = {1, 2, 3, 4, 5}
rating = 1

if rating in ratings:
    print(f'The set contains {rating}')Code language: PHP (php)

Output:

The set contains 1Code language: JavaScript (javascript)

To negate the in operator, you use the not operator. For example:

ratings = {1, 2, 3, 4, 5}
rating = 6

if rating not in ratings:
    print(f'The set does not contain {rating}')
Code language: PHP (php)

Output:

The set does not contain 6Code language: JavaScript (javascript)

Adding elements to a set

To add an element to a set, you use the add() method:

set.add(element)
Code language: JavaScript (javascript)

For example:

skills = {'Python programming', 'Software design'}
skills.add('Problem solving')

print(skills)
Code language: PHP (php)

Output:

{'Problem solving', 'Software design', 'Python programming'}
Code language: JavaScript (javascript)

Removing an element from a set

To remove an element from a set, you use the remove() method:

set.remove(element)
Code language: JavaScript (javascript)

For example:

skills = {'Problem solving', 'Software design', 'Python programming'}
skills.remove('Software design')

print(skills)Code language: PHP (php)

Output:

{'Problem solving', 'Python programming'}Code language: JavaScript (javascript)

If you remove an element that doesn’t exist in a set, you’ll get an error (KeyError). For example:

skills = {'Problem solving', 'Software design', 'Python programming'}
skills.remove('Java')
Code language: JavaScript (javascript)

Error:

KeyError: 'Java'Code language: JavaScript (javascript)

To avoid the error, you should use the in operator to check if an element is in the set before removing it:

skills = {'Problem solving', 'Software design', 'Python programming'}
if 'Java' in skills:
    skills.remove('Java')
Code language: JavaScript (javascript)

To make it more convenient, the set has the discard() method that allows you to remove an element. And it doesn’t raise an error if the element is not in the list:

set.discard(element)
Code language: JavaScript (javascript)

For example:

skills = {'Problem solving', 'Software design', 'Python programming'}
skills.discard('Java')
Code language: JavaScript (javascript)

Returning an element from a set

To remove and return an element from a set, you use the pop() method.

Since the elements in a set have no specific order, the pop() method removes an unspecified element from a set.

If you execute the following code multiple times, it’ll show a different value each time:

skills = {'Problem solving', 'Software design', 'Python programming'}
skill = skills.pop()

print(skill)
Code language: PHP (php)

Removing all elements from a set

To remove all elements from a set, you use the clear() method:

set.clear()
Code language: JavaScript (javascript)

For example:

skills = {'Problem solving', 'Software design', 'Python programming'}
skills.clear()

print(skills)
Code language: PHP (php)

Output:

set()
Code language: JavaScript (javascript)

Frozen a set

To make a set immutable, you use the built-in function called frozenset(). The frozenset() returns a new immutable set from an existing one. For example:

skills = {'Problem solving', 'Software design', 'Python programming'}
skills = frozenset(skills)
Code language: JavaScript (javascript)

After that, if you attempt to modify elements of the set, you’ll get an error:

skills.add('Django')
Code language: JavaScript (javascript)

Error:

AttributeError: 'frozenset' object has no attribute 'add'Code language: JavaScript (javascript)

Looping through set elements

Since a set is an iterable, you can use a for loop to iterate over its elements. For example:

skills = {'Problem solving', 'Software design', 'Python programming'}

for skill in skills:
    print(skill)
Code language: PHP (php)

Output:

Software design
Python programming
Problem solving

To access the index of the current element inside the loop, you can use the built-in enumerate() function:

skills = {'Problem solving', 'Software design', 'Python programming'}

for index, skill in enumerate(skills):
    print(f"{index}.{skill}")
Code language: PHP (php)

Output:

0.Software design
1.Python programming
2.Problem solvingCode language: CSS (css)

By default, the index starts at zero. To change this, you pass the starting value to the second argument of the enumerate() function. For example:

skills = {'Problem solving', 'Software design', 'Python programming'}

for index, skill in enumerate(skills, 1):
    print(f"{index}.{skill}")Code language: PHP (php)

Output:

1.Python programming
2.Problem solving
3.Software designCode language: CSS (css)

Notice that every time you run the code, you’ll get the set elements in a different order.

In the next tutorial, you’ll learn how to perform useful operations on sets such as:

Summary

  • A set is an unordered collection of immutable elements.
Did you find this tutorial helpful ?