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.
- add(): This method adds an element to the set.pythonCopy code
fruits.add("orange")
- update(): This method adds multiple elements to the set.pythonCopy code
fruits.update(["mango", "grape"])
Part 4: Set Methods
Python provides a host of methods that you can use on sets.
- remove(): The remove() method removes the specified element from the set.pythonCopy code
fruits.remove("banana")
- discard(): The discard() method also removes the specified element from the set. However, if the element doesn’t exist, the set remains unchanged. The remove() method would raise an error in such a scenario.pythonCopy code
fruits.discard("kiwi")
- pop(): The pop() method removes and returns an arbitrary set element.pythonCopy code
fruits.pop()
- clear(): The clear() method removes all elements from the set.pythonCopy code
fruits.clear()
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!