Python Sets: Understanding and Usage

🚀 Python for Data Analyst -Understanding Sets in Python (Part 1)-(Post -7) 🔹 What is a Set? A set in Python is: unordered unindexed mutable stores unique elements only can contain different data types does not allow duplicates Example: my_set = {1, 2, 3, 4, 5} print(my_set) 🔹 Key characteristics of sets Order is not guaranteed Duplicates are removed automatically You cannot access items by index like set[0] Sets are implemented internally using hash tables Sets are useful for duplicate removal and fast membership checking 🔹 Creating Sets 1. Using curly braces s = {1, 2, 3, 4} print(s) 2. Creating an empty set s = set() print(type(s)) Important: {} # this creates an empty dictionary, not a set 3. Using set() with other iterables print(set([1, 2, 2, 3, 4])) print(set((1, 1, 2, 3))) print(set("GeeksForGeeks")) print(set(range(3, 8))) 4. Converting dictionary to set d = {'x': 1, 'y': 2, 'z': 3} print(set(d)) Important: When a dictionary is passed to set(), only keys are taken. 🔹 Duplicate Removal One of the best uses of sets is duplicate removal. lst = [1, 2, 2, 3, 4, 4, 5] unique_vals = set(lst) print(unique_vals) 🔹 Can Sets Contain Any Type? Sets can only contain hashable / immutable elements, such as: int float string tuple None They cannot contain mutable / unhashable types like: list dictionary set Reason: Sets use hashing internally, so elements must be stable and hashable. 🔹 Accessing Set Elements Because sets are unordered and unindexed, this is invalid: s[0] # ❌ TypeError Correct ways: 1. Using loop s = {"Geeks", "For", "Python"} for item in s: print(item) 2. Using membership operator print("Geeks" in s) print("Java" in s) 🔹 Adding Elements add() → add a single element s = {1, 2, 3} s.add(4) print(s) If the element already exists, nothing changes. s.add(4) print(s) update() → add multiple elements from an iterable s.update([5, 6]) print(s) update() works with: list tuple set string any iterable Example: s.update("hi") print(s) Each character is added separately. 🔹 Removing Elements remove() Removes a given element. If element is not present, it raises KeyError. s = {1, 2, 3, 4, 5} s.remove(3) print(s) discard() Removes an element if present. If not present, no error is raised. s.discard(10) print(s) pop() Removes and returns any arbitrary element. val = s.pop() print(val) print(s) Important: Because sets are unordered, we cannot predict which element will be removed. clear() Removes all elements and makes the set empty. s.clear() print(s) Output: set() 🔹 Membership Testing Sets are excellent for fast membership checks. my_set = {1, 2, 3, 4, 5} print(3 in my_set) print(10 in my_set) 🔹 Practical Use Case Counting unique words: text = "In this tutorial we are discussing about sets" words = text.split() unique_words = set(words) print(unique_words) print(len(unique_words)) #Python #PythonLearning #DataAnalytics #Sets #LearningInPublic

To view or add a comment, sign in

Explore content categories