Introduction to Python Sets

Welcome, Pythonist! Our focus today is Python sets, which are mutable containers of unique items. With your newfound skills in managing sets, you'll be able to handle any collection of non-duplicated items with ease. Ready? Let's begin!

Sets in Python are user-defined collections of unique items. They're unordered yet mutable. Imagine you've got apples, bananas, and oranges in a basket, and you want only unique fruits. That's where sets come into play, eliminating duplicates and leaving only the unique items behind.

Creating Sets in Python

Creating Python sets is easy. Just enclose your items in {} or use the set() function. Let's try it:

Even though we added 'apple' twice, it appears only once because sets automatically remove duplicates.

Accessing Elements in Sets

Sets don't support access through indexing. However, Python does allow keyword searches with in. Here's how:

Modifying Sets in Python

As mutable entities, sets allow us to add or delete items. Add items using the add() method and remove items with the method. For example:

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal