Introduction

Hello, fellow coders! Welcome back to our Python series on CipherTrick.com. In this tutorial, we’ll explore another data structure that’s a real powerhouse when it comes to handling data – the Set. If you’re looking for ways to handle unique items, Sets are your best bet.

Part 1: What are Sets?

A set in Python is an unordered collection of items that only stores unique items. This means that a set automatically eliminates any duplicates. In Python, sets are written with curly brackets {}.

fruits = {"apple", "banana", "cherry", "apple"}
print(fruits)  # Outputs: {'apple', 'banana', 'cherry'}

Notice that “apple”, which was duplicate in the set, only appears once in the output.

Part 2: Accessing Set Items

Because sets are unordered, you can’t access items in a set by referring to an index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set by using the in keyword.

for fruit in fruits:
    print(fruit)

Part 3: Modifying Sets

While you can’t change the items in a set, you can add new items.

Part 4: Set Methods

Python provides a host of methods that you can use on sets.

Conclusion

Sets in Python are a powerful tool that allows you to handle and operate on unique items efficiently. They become indispensable when you’re working on problems related to set theory, such as finding the union, intersection, or difference between two groups of items. In the next tutorial, we will dig deeper into Functions in Python. So, keep practicing and see you in the next tutorial!