Python Set Collection Tutorial

In this tutorial we learn about one of Python's unordered collection data types, sets.

We cover declaring and initializing a set as well as how to access, change and remove items. We also cover set constructors, and common set functions.

What is a set?

The set data type is one of the sequence, or collection data types in Python, similar to a list.

Like the list collection, a set is mutable, which means its values can change to a degree at runtime. Unlike other collections, a set is unordered and doesn’t support indexing.

How to declare/initialize a set

To initialize a set we give it a name, followed by the assignment operator and comma separated values between curly braces.

Syntax:
 set_name = {value_1, value_2, value_3, ...}
Example: declare / initialize a set
 e_set = {"Monty", 20, 3.14}

How to access values in a set

We can access a set’s items with the indexer in either standalone format or as temporary variable in a loop.

How to access values in a set with the indexer

A set does not support indexing so we cannot access it by index.

Example:
e_set = {"Monty", 20, 3.14}

print(e_set[0])

When we run the example above we’ll get a TypeError saying that a set does not support indexing.

How to access set items in a loop

If we want to access the items in a set we will need to use a for loop .

Example: access set items in a loop
e_set = {"Monty", 20, 3.14}

for item in e_set:
    print(item)

When we run the example above, we can see that we have access to the items.

note The items did not print in the order we initialized them in. Because a set doesn’t have an index, they can’t be indexed in the order we initialize them.

Python sorts a set randomly. As an example, we can run the example code a few more times. In the output we see that the order in which they appear is different each time.

How to change items in a set

While elements in a set must be immutable, the set itself is mutable and can be changed. However, because a set is unordered, we can’t use indexing to change items.

We have two options to add items to a set.

  • add()
  • update()

How to add items to a set

Python allows us to add one or more items to a set that has already been initialized.

How to add an item to a set with the add() function

To add a single item to the set we have to use the add() function.

Syntax:
 set_name.add(item)

We specify the item to add between open and close parentheses.

note Between the set name and add() is a . (dot) operator. This is known as dot notation and is covered in the lesson on classes and objects .

Example: add() an item to a set
e_set = {"Monty", 20, 3.14}

e_set.add("Python")

for item in e_set:
    print(item)

When we run the example above we can see that the word “Python” was added to the set.

How to add items to a set with the update() function

To add multiple items to a set we have to use the update() function.

Syntax:
 set_name.update([item_1, item_2, item_3, ...])

When updating a list with multiple items we use list syntax and wrap our items with square brackets.

Example: update() a set with an item
e_set = {"Monty", 20, 3.14}

e_set.update(["Python", "Holy", "Grail"])

for item in e_set:
    print(item)

When we run the example above we can see that all the items were added successfully.

Remove items from a set

We have two options to remove items from a set.

  • remove()
  • discard()

How to remove items from a set with the remove() function

To remove an item from a set we can call the remove() function on it.

Syntax:
 set_name.remove(item)
Example: remove() an item from a set
e_set = {"Monty", 20, 3.14}

e_set.remove("Monty")

for item in e_set:
    print(item)

When we run the example above we can see that the word “Monty” was removed from the set.

If the item we want to remove does not exist, the interpreter will raise an error.

Example:
e_set = {"Monty", 20, 3.14}

e_set.remove("Python")

for item in e_set:
    print(item)

When we run the example above we get a KeyError for the word “Python” because it doesn’t exist in the set.

Output:
 KeyError: 'Python'

How to remove items from a set with the discard() function

Another way to remove an item from a set is to use the discard() function.

Syntax:
 set_name.discard(item)
Example: discard() items from a set
e_set = {"Monty", 20, 3.14}

e_set.discard("Monty")

for item in e_set:
    print(item)

When we run the example above we can see that the word “Monty” was discarded from the set.

If the item we want to discard does not exist, the interpreter will not raise an error.

Example:
e_set = {"Monty", 20, 3.14}

e_set.discard("Python")

for item in e_set:
    print(item)

When we run the example above we don’t get any errors even though the word “Python” does not exist in the set.

How to clear a set

To clear a set we use the clear() function without any parameters.

Syntax:
 set_name.clear()
Example: clear() items in a set
e_set = {"Monty", 20, 3.14}

e_set.clear()

for item in e_set:
    print(item)

When we run the example above no results are printed because the set has nothing inside of it after the clear.

note Clearing a set only removes its values. The set is not deleted, it still exists.

How to delete a set

To delete a set we use the del keyword.

Syntax:
 del set_name
Example: delete a set
e_set = {"Monty", 20, 3.14}

del e_set

for item in e_set:
    print(item)

When we run the example above we see a NameError. The interpreter cannot find the name “e_set” because after the delete it doesn’t exist anymore.

How to create a set with the set constructor

We can create a set by using a set constructor.

tip Even though we learn about them here, constructors are a concept of classes. We learn more about classes in the object oriented programming lesson on classes and objects .

To create a set using the set constructor we use the keyword set with the values we want between double parentheses.

Syntax:
 set_name = set((item_1, item_2, item_3))
Example: create a set with the constructor
e_set = set(("Monty", 20, 3.14))

for item in e_set:
    print(item)

Common set functions

The following table shows some common functions used with sets:

FunctionDescription
add()Add an item to a set
clear()Clear all items from a set
copy()Return a full copy of a set
difference_update()Removes the items in this set that also exists in another specified set
discard()Remove an item from a set
intersection_update()Removes the items in this set that doesn’t exist in another specified set
issubset()Returns whether another set contains this full set
issuperset()Returns whether this set caontains another full set
pop()Removes the last element from a set
remove()Removes a specific element from a set

Summary: Points to remember

  • A set is like a variable that can store multiple separate values.
  • We store set values by writing them between curly braces, and separating each value with a comma.
  • We access set values with the indexer. That is to say, the index number that corresponds to the item’s location in the set.
  • Sets are mutable, but item values cannot be changed because sets are unordered.
  • We can add items to a set with the add() or update() function.
  • We can remove items from a set with the remove() or discard() function.
  • We clear all values from a set with the clear() function. This will only empty the set, not delete it entirely.
  • We delete a set entirely with the del keyword.