Sets in Python

Sets are one of the interesting collection types in Python. First introduced in version 2.4, sets allow you to create a collection object that is unordered, unique, immutable and supports operations corresponding to mathematical set theory.

sets can be created in two ways.

The new syntax looks clean and adheres to the mathematical notation of a set. Note that even though you can use the new set syntax notation to create non-empty sets; for creating a empty set you still need to use the built-in set method.

Note: Initially the set type was available as a external module but it has been deprecated since version 2.6. So before 2.6 you had to import the module to use the set type.

Now the built-in set/frozenset types replace the old set module.

Uses of the set type

Listing the benefits of something out of context can be difficult. But lets us give it a shot. Because sets store only one one item of each,, they can be used to filter duplicates from other collections – by converting a list to a set and back.

You can check for string difference using sets.

Besides filtering and differences, you can do the usual mathematical set operations.

You can also use the Python 3.x version while creating sets.

You can also write the above operations like below. Although I prefer the above notation.

Adding and deleting elements of a set

We can add and delete elements of a set using various built-in methods.

We can use the len() method to test for emptiness.

Types of Set

There are currently two built-in set types, set and frozenset. The set we saw before in the post is the mutable kind because the contents can be changed using methods like add() and remove(). The other type is the frozenset type, which is immutable and – its contents cannot be altered after it is created. Adding and deleting is not permitted for a frozen set.

You can test your Python code using the online code editor.

Leave a Reply

Your email address will not be published. Required fields are marked *