Sets in Python

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 Tuple in Python?

The syntax for creating a Sets is,

 

setName = {value1, value2, value3, and so on.. }
  • First you give the set a name
  • 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 [].

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"}
print(sport_set)
print(type(sport_set))

 

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:
    print(i)

 

We will get

 

Tennis 
Football 
Ice Hockey

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