Python Sets: Unique Data Collection & Math Operations

 PYTHON JOURNEY - Day 38 / 50..!! TOPIC – Python Sets Today I explored Sets — a unique data collection type in Python that is all about uniqueness and mathematical operations! 1. Creating a Set Sets use curly braces {} just like dictionaries, but they only contain single values, not pairs. Python numbers = {1, 2, 3, 4, 5, 5, 5} print(numbers) # Output: {1, 2, 3, 4, 5} (Duplicates are automatically removed!) 2. Unordered & Unindexed Unlike lists, sets do not have a fixed order. You cannot access items using an index like [0]. Python fruits = {"Apple", "Banana", "Cherry"} # print(fruits[0]) # This will cause an ERROR 3. Set Operations (The Power of Math) Python sets allow you to perform powerful operations like Union and Intersection. Python set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1.union(set2)) # Output: {1, 2, 3, 4, 5} (Combines both) print(set1.intersection(set2)) # Output: {3} (Items present in both) Why Use Sets? Remove Duplicates: The easiest way to clean a list of repeating items is to convert it to a set. Membership Testing: Checking if an item exists in a set is much faster than in a list. Data Comparison: Perfect for finding what two groups of data have in common (or what makes them different). Mini Task Write a program that: Creates a list with duplicate numbers: [1, 2, 2, 3, 4, 4, 5]. Converts that list into a Set to automatically remove the duplicates. Creates a second set {4, 5, 6, 7} and prints the Intersection between the two sets. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories