Sets in Python part 1

Sets in Python part 1

What are sets?, how we create them?, and basic operations.

What are sets?

Sets are one of Python's 4 built-in data types used to store data collections.

Sets in python are similar to sets in mathematics, so they share characteristics. For example, both stores unordered, and unindexed data. Sets can't store multiple instances of the same data.

The python representation of sets also doesn't allow changing the value of the items, but we can remove and add items. Set items can be of any data type, and different data types can be contained in a set.

How do we create a set?

Similarly to how we create dictionaries in Python, we use curly brackets to create sets.

To create an empty set, we use the set() function. We can also use the set(<iter>) function to create sets, passing an iterable as an argument.

Set operations

Checking length

We use the len(<set>) function to the length, the number of elements, of the set.

Checking membership

To test if an item forms part of the set, we use the in, and not in operators.

Adding

To add items to a set, we can use the add(<elem>) method, which only accepts one item at a time and can accept tuples as an item.

We can also use the update(<elem>) method, which can take lists, strings, tuples, and other sets as its arguments.

Removing

We have 4 ways to remove elements from a set.

The remove(<elem>) method removes <elem> from the set but raises a KeyError exception if <elem> doesn't exist in the set.

The discard(<elem>) method does the same as remove(<elem>), but instead of raising an exception does nothing if <elem> doesn't exist in the set.

The pop() method removes an arbitrary element from the set. If the set is empty raises a KeyError exception.

At last, the clear() method is used to remove all the elements from the set.

Further reading

Sets in python - Real Python

Python Sets - GeeksforGeeks

Python sets - W3Schools

Python - Set Methods - W3Schools

Mathematics | Set Operations (Set theory) - GeeksforGeeks


Format

With this blog post, I'm experimenting with the format for the code block. Instead of using code block with Markdown, I use Replit embeds so that you can see and execute the code.

What will you prefer in the future Markdown, GH Gists, or Replits?