Sets in Python

Keywords: sets, tuple, array, list

Lists python programming

Sets in Python are a collection of elements that have no particular order and lack indexing.

What is a set in Python?

Like tuples and arrays, sets in Python are a collection of objects. The elements in sets has no particular order and therefore lack indexing. Thus, it is not possible to remove an individual element from a set.

The elements in sets has no particular order and therefore lack indexing

How to create a set in Python?

The steps for creating sets in Python is,

  • First you give the set a name, followed by equal sign =
  • Then assigns all values within the curly brackets , where each value is separated by a comma  “,”.
  • Note that a Set is created with curly brackets, unlike the array that is created with brackets [], and the tuple that is created with parentheses ()

Syntax: Sets in Python

If we follow the steps above and enter them in the code editor

# Syntax creating a set in Python
setName = {value1, value2, value3, and so on.. }

Example: How to create Sets in Python

Let’s take a quite simple example on how to create a Set in Python

sport_set = {"Tennis", "Football", "Ice Hockey"}

The result then becomes

{'Tennis', 'Football', 'Ice Hockey'}
<class 'set'>

Note that there are no indexes in sets. Thus, you cannot remove a single element from the set that you can with tuple and arrays.

However, you can iterate through the entire list with a for loop:

for i in sport_set:

We will get

Ice Hockey

For more information about Sets in Python we recommend the Python Docs website