Python sets

Just like the lists or tuples, a set in python is also one of the collection types. A set is unordered, unindexed, and unchangeable. It is written using curly braces.

Example of a set:

cities = {'Delhi', 'Mumbai', 'Hyderabad', 'Bhopal'}

print(cities)

Output:

{‘Delhi’, ‘Mumbai’, ‘Hyderabad’, ‘Bhopal’}

Set items are unordered

It means that the items do not have a defined order in a set. They may appear in a different order every time you use them. Moreover, they cannot be referred to by any index.

A set is unchangeable

Once you create a set, it cannot be changed. However, you can remove items and add new ones.

Duplicate items are not allowed in a set

A set cannot have multiple items with the same value. If you try to do so, the duplicate values will be ignored.

For example:

cities = {'Delhi', 'Mumbai', 'Delhi', 'Hyderabad', 'Bhopal'}

print(cities)

Output:

{‘Mumbai’, ‘Delhi’, ‘Hyderabad’, ‘Bhopal’}

How to determine the length of a set?

To find out the number of items in a set, we can use the len() function.

For example

cities = {'Delhi', 'Mumbai', 'Hyderabad', 'Bhopal'}

print(len(cities))

Output:

4

Data types in a set

Items in a set can be of any data type. They can be string, integers or boolean values.

cities = {'Delhi', 'Mumbai', 'Hyderabad', 'Bhopal'}
ids = {1,12,45,24,56}
marks = {True, False}

print(cities)
print(ids)
print(marks)

Output:

{‘Delhi’, ‘Mumbai’, ‘Hyderabad’, ‘Bhopal’}

{1,12,45,24,56}

{True, False}

Not only this, but a set can have mixed data type values.

sampleset = {'Delhi', 24, True, 'mango'}

Type of a set

A set is defined as an object with the data type ‘set’.

For example

cities = {'Delhi', 'Mumbai', 'Hyderabad', 'Bhopal'}

print(type(cities))

Output:

<class ‘set’>

Note: We have used the type function to determine the set’s type. The type function in python is used to get the type of an object.