A frozen set in Python is created using the frozenset() function. It is similar to a normal set, but the main difference is that a frozen set is immutable, which means its elements cannot be changed, added, or removed after it is created. Frozen sets are useful when you want a collection of unique elements that should remain constant during the execution of a program. numbers = frozenset([1, 2, 3, 4, 5]) print(numbers) Output frozenset({1, 2, 3, 4, 5}) In this example, the numbers are stored inside a frozen set and cannot be modified later. Example 2: Frozen Set Removes Duplicate Values Like normal sets, frozen sets store only unique values. If duplicate elements are provided when creating the frozen set, Python automatically removes the repeated values and keeps only one copy of each element. data = frozenset([1, 2, 2, 3, 4, 4, 5]) print(data) Output frozenset({1, 2, 3, 4, 5}) Here, the numbers 2 and 4 appear twice in the list, but the frozen set keeps only one instance of each number. Example 3: Creating Frozen Set from a List Description: A frozen set can be created from different iterable objects such as lists, tuples, or strings. When a list is converted into a frozen set, all its elements become part of an immutable set. my_list = ["apple", "banana", "orange"] fruits = frozenset(my_list) print(fruits) Output frozenset({'apple', 'banana', 'orange'}) In this example, the list of fruits is converted into a frozen set. Example 4: Creating Frozen Set from a String Description: When a string is passed to the frozenset() function, each character in the string becomes an element of the frozen set. Since sets store only unique elements, repeated characters will appear only once. letters = frozenset("python") print(letters) Output frozenset({'p', 'y', 't', 'h', 'o', 'n'}) Each letter of the word python becomes a separate element in the frozen set. Example 5: Frozen Set Union Operation Description: Frozen sets support many mathematical operations such as union, intersection, and difference. The union operation combines the elements of two frozen sets and returns a new frozen set containing all unique elements. A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) print(A.union(B)) Output frozenset({1, 2, 3, 4, 5, 6}) In this example, the union operation merges both frozen sets and removes duplicate elements. #python #pythonforbeginners #pythonprogramming #python #pythondatastructure #pythondatatype #education #intersectionofsets #linkedinfollowers
More Relevant Posts
-
⚡ How do loops affect performance and memory usage in Python? When working with large datasets, the way we write loops can affect both performance and memory usage. A loop simply repeats the same operation over multiple elements. As the dataset grows, the number of operations grows as well, so choosing the right approach becomes important. 🔹 Traditional loop vs List Comprehension Suppose we want to compute the square of numbers in a list. A traditional loop might look like this: numbers = [1,2,3,4,5] squares = [ ] for n in numbers: squares.append(n**2) This works fine, but each iteration performs several steps: 1️⃣ Access the element 2️⃣ Compute the value 3️⃣ Append it to the list Python offers a cleaner and often faster approach called List Comprehension: squares = [n**2 for n in numbers] ✅ Same result ✅ Shorter, more readable code ✅ Often faster due to internal optimizations 🔹 Nested loops and Time Complexity ⏱ Performance issues become more noticeable with nested loops: for i in range(n): for j in range(n): print(i, j) If the input size is n, the number of operations becomes: n × n 📊 Time Complexity = O(n²) This means execution time grows rapidly as the dataset increases. Example: • n = 10 → ~100 operations • n = 100 → ~10,000 operations • n = 1000 → ~1,000,000 operations ⚠️ That’s why nested loops can slow down programs when dealing with large datasets. 🔹 Using built-in functions instead of loops Sometimes we don’t need to write loops at all, since Python provides optimized built-in functions. Example: numbers = [1,2,3,4] total = sum(numbers) Other useful functions include: • map() → applies a function to every element: squares = list(map(lambda x: x**2, numbers)) • filter() → selects elements that satisfy a condition: even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) These approaches often produce cleaner and more expressive code. 🔹 Memory efficiency with Generators 💡 With very large datasets, memory usage becomes critical. numbers = [x for x in range(1000000)] This stores all values in memory. Using a generator instead: numbers = (x for x in range(1000000)) Values are generated one at a time during iteration, reducing memory usage. ➡️ This is especially useful when processing large data streams. 💡Python Performance Tips ✔ Use List Comprehensions for cleaner, faster loops ✔ Be careful with nested loops (O(n²)) ✔ Use built-in functions like sum(), map(), filter() ✔ Use generators for better memory efficiency Efficient code in Python is about choosing the right tool for the task. #Python #PythonProgramming #LearnPython #SoftwareEngineering #Coding
To view or add a comment, sign in
-
Python Prototypes vs. Production Systems: Lessons in Logic Rigor 🛠️ This week, I stopped trying to write code that "just works" and started writing code that refuses to crash. As an aspiring Data Scientist, I’m learning that stakeholders don’t just care about the output—they care about uptime. If a single "typo" from a user kills your entire analytics pipeline, your system isn't ready for the real world. Here are the 4 "Industry Veteran" shifts I made to my latest Python project: 1. EAFP over LBYL (Stop "Looking Before You Leap") In Python, we often use if statements to check every possible error (Look Before You Leap). But a "Senior" approach often favors EAFP (Easier to Ask for Forgiveness than Permission) using try/except blocks. Why? if statements become "spaghetti" when checking for types, ranges, and existence all at once. Rigor: A try block handles the "ABC" input in a float field immediately, keeping the logic clean and the performance high. 2. The .get() Method: Killing the KeyError Directly indexing a dictionary with prices[item] is a ticking time bomb. If the key is missing, the program dies. The Fix: I’ve switched to .get(item, 0.0). This allows for a "Default Value" fallback in a single line, preventing "Dictionary Sparsity" from breaking my calculations. 3. Preventing the "System Crush" Stakeholders hate downtime. I implemented a while True loop combined with try/except for all user inputs. The Goal: The program should never end unless the user explicitly chooses to "Quit." Every "bad" input now triggers a helpful re-prompt instead of a system failure. 4. Precision in Data Type Conversion Logic errors often hide in the "Conversion Chain." I focused on the transition from String (from input()) to Int (for indexing). The Off-by-One Risk: Users think in "1-based" counting, but Python is "0-based." I’ve made it a rule to always subtract 1 from the integer input immediately to ensure the correct data point is retrieved every time. The Lesson: Coding is about the architecture of the "Why" just as much as the syntax of the "What." [https://lnkd.in/gvtiAKUb] #Python #DataScience #CodingJourney #CleanCode #BuildInPublic #SoftwareEngineering #SeniorDataScientist #TechMentor
To view or add a comment, sign in
-
-
Same language. Four completely different power levels. 🐍 This is every Python developer's journey. And if you're still in panel 1, let me tell you what nobody else will 👇 💭 PANEL 1: BASIC CODING x = 10 print("Hello") You're sweating. Python looks friendly but feels impossible. The snake is tiny but you're terrified. Why? Because you're thinking like a human trying to talk to a machine. Reality: Everyone starts here. Everyone struggles. The snake stays small until you feed it. 📊 🎯 PANEL 2: LEARNING PYTHON def greeting(): print(x) Now it clicks. Functions make sense. Imports make sense. The snake wraps around you like a friend. You're not fighting Python anymore. You're dancing with it. This is where most tutorials end. And where most developers get stuck thinking they "know Python." 💡 🔥 PANEL 3: USING LIBRARIES NumPy. Pandas. Requests. Pip. The snake got confident. You got powerful. You're not writing basic scripts anymore. You're manipulating datasets. Making API calls. Building real tools. This is where beginners become developers. Where code becomes solutions. ⚡ 🐉 PANEL 4: PYTHON + DJANGO + AI The snake is a BEAST now. Muscular. Unstoppable. Django for full-stack web apps. AI models. Neural networks. Production systems. You're not just using Python. You're wielding it. 🚀 💪 THE PATTERN EVERYONE MISSES Most people give up between Panel 1 and Panel 2. They see "def greeting():" and think it's too hard. They quit right before it gets easy. The snake doesn't become powerful overnight. It grows with every library you learn. Every project you build. Every bug you fix. 💭 🚨 THE UNCOMFORTABLE TRUTH Panel 1 developers and Panel 4 developers use the SAME language. The difference? One stopped at syntax. The other kept building. Python isn't hard. Stopping too early is hard. 🎯 📌 WHERE ARE YOU? Panel 1: Struggling with basics → Keep going, everyone was here Panel 2: Comfortable with syntax → Start building real projects Panel 3: Using libraries → Master 2-3 deeply, not 20 superficially Panel 4: Full stack + AI → You're not learning anymore, you're creating The snake grows with you. But only if you keep feeding it. 🔥 Which panel are you in right now? Be honest 👇 #Python #Programming #WebDevelopment #AI #MachineLearning #Django #CodingJourney #TechSkills #SoftwareDevelopment #LearnToCode
To view or add a comment, sign in
-
-
🚀 Python Dictionary Mastery: Complete Guide with Definitions, Examples & Outputs 🔹 1. What is a Dictionary? 📘 Definition: A Dictionary stores data in key-value pairs 👉 Example: student = {"name": "Madhav", "age": 20} 📌 Features: ✔ Ordered (Python 3.7+) ✔ Mutable (can change) ✔ No duplicate keys ✔ Keys must be immutable (str, int, tuple) 🔹 2. Creating a Dictionary (3 Ways) ✅ Method 1: Using {} cohort = {"course": "Python", "level": "Beginner"} print(cohort) 🟢 Output: {'course': 'Python', 'level': 'Beginner'} ✅ Method 2: Using dict() student = dict(name="Madhav", age=20) print(student) 🟢 Output: {'name': 'Madhav', 'age': 20} ✅ Method 3: Using List of Tuples student = dict([("name", "Madhav"), ("age", 20)]) print(student) 🟢 Output: {'name': 'Madhav', 'age': 20} 📌 Important Note: 👉 dict() constructor supports tuples & keyword arguments 🔹 3. Accessing Values ✅ Using [] student = {"name": "Madhav", "age": 20} print(student["name"]) 🟢 Output: Madhav ⚠️ Error if key not found ✅ Using .get() (Safe Way) print(student.get("age")) print(student.get("email", "Not Found")) 🟢 Output: 20 Not Found 📌 Why use get()? 👉 Avoids errors & allows default values 🔹 4. Dictionary Methods student = {"name": "Madhav", "age": 20, "grade": "A"} 🔸 keys() print(student.keys()) 🟢 Output: dict_keys(['name', 'age', 'grade']) 🔸 values() print(student.values()) 🟢 Output: dict_values(['Madhav', 20, 'A']) 🔸 items() print(student.items()) 🟢 Output: dict_items([('name', 'Madhav'), ('age', 20), ('grade', 'A')]) 🔸 Add / Update student["city"] = "Mathura" student["age"] = 21 🔸 Remove Data student.pop("age") 🟢 Output: 21 📌 Yes 👉 .pop() returns deleted value 🔹 5. Dictionary Iteration (Loops) student = {'name': 'Madhav', 'grade': 'A', 'city': 'Mathura'} 🔸 Loop Keys for key in student: print(key) 🟢 Output: name grade city 🔸 Loop Values for value in student.values(): print(value) 🟢 Output: Madhav A Mathura 🔸 Loop Key + Value for k, v in student.items(): print(k, v) 🟢 Output: name Madhav grade A city Mathura 🔹 6. Nested Dictionary 📘 Definition: Dictionary inside another dictionary students = { "s1": {"name": "Madhav", "age": 20}, "s2": {"name": "Keshav", "age": 25} } 🔸 Access Data print(students["s1"]["name"]) 🟢 Output: Madhav 📌 Use Case: Complex structured data (API, JSON) 🔹 7. Dictionary Comprehension 📘 Definition: One-line dictionary creation squares = {x: x*x for x in range(1, 6)} print(squares) 🟢 Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 🔸 With Different Expression double = {x: x+x for x in range(1, 6)} 🟢 Output: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10} 📌 Pro Tip: 👉 Can include conditions also 🔥 Important Interview Q&A ❓ Can keys be changed? 👉 ❌ No (keys must be immutable) ❓ Can keys be duplicate? 👉 ❌ No ❓ Which data types allowed as keys? 👉 ✔ String, Number, Tuple ❓ Why use dictionary? 👉 ✔ Fast lookup 👉 ✔ Structured data storage #Python #DataStructures #Coding #Learning #Programming #CareerGrowth
To view or add a comment, sign in
-
Lists in Python A versatile data structure used to store multiple items in a single variable. 🎯 1. What is a List? Lists are ordered, mutable collections of items that allow duplicate elements. They are defined using square brackets []. 🎯 2. Creating a List A list by placing comma-separated values inside square brackets. python # Example my_list = [1, "Hello", 3.14, True] 🎯 3. Accessing List Elements & Indexing zero-based indexing to access elements. python # Example fruits = ["apple", "banana", "cherry"] print(fruits[0]) # First element print(fruits[-1]) # Last element 🎯 4. List Slicing Access a range of elements Syntax [start:stop:step]. python # Example numbers = [10, 20, 30, 40, 50, 60] print(numbers[1:4]) # From index 1 up to (but not including) 4 print(numbers[::-1]) # Reverse the list Output: [20, 30, 40] [60, 50, 40, 30, 20, 10] 🎯 5. Modifying Lists Lists are mutable, meaning you can change their items. python # Example fruits = ["apple", "banana", "cherry"] fruits[1] = "blueberry" # Change index 1 print(fruits) Output: [apple, blueberry, cherry] 🎯 6. List Methods append() : Adds an item to the end. python fruits.append("orange") insert() : Adds an item at a specific position. python fruits.insert(1, "mango") remove() : Removes the first occurrence of a specific value. python fruits.remove("banana") pop() : Removes and returns an item at a specific index (or the last item if no index is specified). python last_item = fruits.pop() sort() : Sorts the list in place. 🎯 List Comprehensions A list comprehension offers a concise way to create lists in Python based on existing lists or iterables. Basic Syntax: new_list = [expression for item in iterable if condition] 🎯 1. Creating a List of Squares Instead of using a for loop to append squares, you can do it in one line. python # Traditional loop squares = [] for x in range(1, 6): squares.append(x*2) 🎯 List comprehension squares = [x*2 for x in range(1, 6)] print(squares) Output: [1, 4, 9, 16, 25] 🎯 2. Filtering with if Condition You can add a condition to filter elements from the original list. python numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Get only even numbers evens = [x for x in numbers if x % 2 == 0] print(evens) Output: [2, 4, 6, 8, 10] 🎯 3. Transforming Strings You can apply string methods like .upper() during creation. python fruits = ["apple", "banana", "cherry"] # Convert all to uppercase upper_fruits = [fruit.upper() for fruit in fruits] print(upper_fruits) Output: ['APPLE', 'BANANA', 'CHERRY'] 🎯 4. Flattening a Nested List This is a highly efficient way to turn a list of lists into a single flat list. python nested_list = [[1, 2], [3, 4], [5, 6]] # Flatten the list flatlist = [item for sublist in nestedlist for item in sublist] print(flat_list) Output: [1, 2, 3, 4, 5, 6] #PythonProgramming #PythonList #DataScience #CodingTips #PythonTutorial #SoftwareDevelopment #Programming
To view or add a comment, sign in
-
Day 27 --Lambda Functions in Python Lambda Functions are small, anonymous functions that can be written in a single line. They are useful when you need a quick function for a short period of time and don’t want to formally define it using def. 🔹 Basic Syntax lambda arguments: expression 🔹 Example add = lambda a, b: a + b print(add(5, 3)) Output: 8 Here, the lambda function takes two arguments and returns their sum. 🔹 Using Lambda with map() map()--->The map() function is used to apply a specific function to every item in an iterable such as a list, tuple, or set. It returns a map object, so we usually convert it to a list to see the result. MAP SYNTAX:-map(function, iterable) function → the function you want to apply iterable → the list, tuple, or other collection of items EXAMPLE : Using Lambda with map() numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) Output: [1, 4, 9, 16, 25] 🔹 Using Lambda with filter() FILTER()--->The filter() function is used to select elements from an iterable based on a condition. It returns only the elements that satisfy the condition. SYNTAX:-filter(function, iterable) function → a function that returns True or False iterable → the collection of items to filter EXAMPLE : Using Lambda with filter() numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) Output: [2, 4, 6] EXAMPLE : Using Lambda with sorted() numbers =[1,2,3,4,5,6] sorted(numbers, key=lambda x:-x)# [6, 5, 4, 3, 2, 1] Key Points *Lambda functions are anonymous functions. *They are written in a single expression. *Commonly used with functions like map(), filter(), and sorted(). *Useful for short, simple operations. Learning concepts like this helps me understand how Python can write clean and concise code. Do you prefer lambda or regular def functions? Drop your answer below 👇 #Python #PythonLearning #CodingJourney #Programming
To view or add a comment, sign in
-
-
✅ Week 2 of 180 — Python Lists are basically a Swiss Army knife! 🔪 Last session was Strings — fixed, immutable, locked. 🔒 Today? We unlocked something FAR more powerful. 🔓 Lists in Python — and honestly this changes EVERYTHING. 👇 🤔 So what IS a List? A List is an ordered, mutable collection of items that can hold multiple values — including different data types all in one place! fruits = ["apple", "banana", "cherry"] mixed = ["Alice", 30, True, 3.14] # yes, all in ONE list! 😲 ✅ 4 Key Properties: 📌 Ordered — every item has a fixed index position ✏️ Mutable — you can change, add or remove items freely 🔁 Allows Duplicates — same value can appear multiple times 🎲 Mixed Types — strings, ints, booleans all together! 📍 List Indexing — works exactly like Strings! nums = [10, 20, 30, 40, 50] # 0 1 2 3 4 ← positive index # -5 -4 -3 -2 -1 ← negative index print(nums[0]) # 10 → first item print(nums[-1]) # 50 → last item If you understood String indexing last session — congrats, you already know List indexing! 😄 ✂️ List Slicing — same syntax as Strings! nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] → index 1 to 3 print(nums[::-1]) # [50, 40, 30, 20, 10] → REVERSED! 🔄 Python really said: "Learn it once, use it everywhere." 😂 🛠️ List Methods — the full toolkit: fruits = ["apple", "banana", "cherry"] fruits.append("kiwi") # adds to END fruits.insert(1, "mango") # inserts at index 1 fruits.remove("banana") # removes first occurrence fruits.pop(2) # removes & returns at index 2 fruits.sort() # sorts ascending fruits.reverse() # reverses the list fruits.clear() # removes ALL items new = fruits.copy() # creates a copy 🔥 The BIG difference from Strings: Strings → IMMUTABLE → methods return a NEW string Lists → MUTABLE → methods change the original list directly! # Strings - must reassign s = "hello" s = s.upper() # must save it back ✅ # Lists - changes happen in place! fruits.append("kiwi") # original list is updated automatically ✅ This tripped me up at first. Now it makes total sense! 😄 💡 Week 2 Summary so far: → Strings = read-only text with powerful methods 📖 → Lists = flexible, editable collections of anything 🗂️ Both use the same indexing and slicing — Python is beautifully consistent! 🐍 📅 Week 2 / 180 — Lists: DONE! ✅ Still going strong on my 6-Month GenAI & Agentic AI Certificate Program 🏛️ IIT Patna Certified print("Lists understood. Building momentum! 🚀") 💪 💬 Which List method do you use the most in your projects? Drop it below! 👇 ♻️ Repost if this helped you understand Python Lists better! #Python 🐍 #Lists #ListMethods #Week2 #GenAI 🤖 #IITPatna 🏛️ #LearningInPublic #100DaysOfCode #PythonBasics #DataStructures #CodingJourney #AgenticAI #NeverStopLearning 🚀 #BuildInPublic #AIForDevelopers
To view or add a comment, sign in
-
-
🐍 *Don’t Overwhelm to Learn Python, Python is Only This Much* 1. Variables & Data Types - int - float - str - bool - list - tuple - set - dict - NoneType 2. Variable Declaration - Assignment using = - Multiple assignments - Swapping values 3. Operators - Arithmetic: + - * / // % ** - Comparison: ==!= > < >= <= - Logical: and or not - Membership: in, not in - Identity: is, is not 4. Control Flow - if, elif, else - match-case (Python 3.10+) 5. Loops - for loop - while loop - break, continue, pass - range() - enumerate() 6. Functions - def keyword - Arguments and Return - Default arguments - *args, **kwargs - Lambda functions 7. Data Structures - Lists: - Tuples: (1, 2, 3) - Sets: {1, 2, 3} - Dicts: {"key": "value"} - List / Dict Comprehension 8. Strings - f-strings -.upper(),.lower() -.strip(),.split(),.join() - Slicing and indexing 9. Error Handling - try, except, else, finally - raise keyword - Custom exceptions 10. File Handling - open(), read(), write() - Modes: 'r', 'w', 'a', 'rb', 'wb' - with context manager 🔥 ADVANCED CONCEPTS 11. OOP (Object-Oriented Programming) - Class & Object - __init__() - Inheritance - Encapsulation - Polymorphism - @staticmethod, @classmethod - __str__, __repr__ 12. Decorators - @decorator_name - Function wrappers - Use cases like logging, timing, auth 13. Generators & Iterators - yield keyword - Generator expressions - __iter__(), __next__() 14. Modules & Packages - import and from - Custom modules - __init__.py - pip install package 15. Comprehensions - List comprehension - Dict comprehension - Set comprehension - Conditional comprehensions 16. Lambda + Functional Programming - lambda functions - map(), filter(), reduce() - zip(), any(), all() 17. Regular Expressions - import re - re.search(), re.match() - re.findall(), re.sub() 18. Working with JSON & APIs - json.dumps() & json.loads() - requests.get(), requests.post() - API response parsing 19. Asynchronous Programming - async / await - asyncio module - Event loops 20. Date and Time - datetime module - strftime() / strptime() - timedelta 21. Virtual Environment & pip - venv for project isolation - pip install, pip freeze - requirements.txt 22. Popular Libraries - NumPy – arrays, math ops - Pandas – data analysis - Matplotlib / Seaborn – data viz - Scikit-learn – ML - Flask / Django – web apps - Tkinter – GUI - OpenCV – image processing 23. Testing - unittest - pytest - Test case creation, assertions 24. File System & OS - os, shutil modules - Path handling - Directory management 25. Pythonic Principles - List unpacking - zip(), enumerate() - with statements - Idiomatic if/else - EAFP vs LBYL *Double tap ❤️ for more*
To view or add a comment, sign in
-
🔹 Sets in Python (With Examples, Outputs & Key Points) 🔹 👉 What is a Set? A Set is an unordered collection of unique elements ✔️ No duplicate values ✔️ No indexing (cannot access via position) 💡 Key Characteristics ✔️ Unordered → No fixed order (output may change) ✔️ Unique Elements → Duplicates automatically removed ✔️ Mutable → Can add/remove elements ✔️ Immutable Elements Only → Items must be int, string, tuple ⚙️ Creating Sets ✅ Method 1: Curly Brackets my_set = {1, 2, 3} print(my_set) print(type(my_set)) Output: {1, 2, 3} ✅ Method 2: set() Constructor my_set2 = set([4, 5, 6]) print(my_set2) Output: {4, 5, 6} ⚠️ Important Note empty = {} print(type(empty)) Output: <class 'dict'> ❌ ✔️ Correct way: empty_set = set() print(type(empty_set)) Output: <class 'set'> ✔️ 🔧 Adding Elements numbers = {1, 2, 3} numbers.add(100) print(numbers) Output (order may vary): {1, 2, 3, 100} ❌ Removing Elements fruits = {'apple', 'mango', 'banana'} fruits.remove('banana') print(fruits) fruits.discard('apple') print(fruits) Output: {'apple', 'mango'} {'mango'} ⚠️ Important Difference .remove() → ❌ Error if item not found .discard() → ✔️ No error 📊 Set Operations set1 = {1, 2, 3} set2 = {3, 4, 5} ✅ 1. Union (Combine all unique elements) ✔️ Pattern 1 (Operator): print(set1 | set2) Output: {1, 2, 3, 4, 5} ✔️ Pattern 2 (Method): print(set1.union(set2)) ✅ 2. Intersection (Common elements) ✔️ Pattern 1: print(set1 & set2) ✔️ Pattern 2: print(set1.intersection(set2)) ✔️ Pattern 3 (Multiple sets): set3 = {3, 6} print(set1.intersection(set2, set3)) Output (example): {3} ✅ 3. Difference (Only in first set) ✔️ Pattern 1: print(set1 - set2) ✔️ Pattern 2: print(set1.difference(set2)) ✔️ Pattern 3 (Reverse difference): print(set2 - set1) Output: {1, 2} ✅ 4. Symmetric Difference (Non-common elements) ✔️ Pattern 1: print(set1 ^ set2) ✔️ Pattern 2: print(set1.symmetric_difference(set2)) print(set1) Output: {1, 2, 4, 5} 🔁 Iteration (Loop Through Set) fruits = {"Apple", "Banana", "Cherry"} for fruit in fruits: print(fruit) Output (order may vary): Banana Apple Cherry ✨ Set Comprehension ✅ Basic Example squares = {x**2 for x in range(1, 6)} print(squares) Output: {1, 4, 9, 16, 25} ✅ With Condition even_squares = {x**2 for x in range(1, 11) if x % 2 == 0} print(even_squares) Output: {64, 4, 36, 100, 16} 🚀 Practical Use Cases ✔️ Remove Duplicates lst = [1, 2, 2, 3, 3, 4] print(set(lst)) Output: {1, 2, 3, 4} ✔️ Membership Testing (Fast) nums = {1, 2, 3} print(2 in nums) Output: True ✔️ Unique Data in Analysis tags = ["python", "ai", "python", "ml"] print(set(tags)) Output: {'python', 'ai', 'ml'} 📌 Final Important Notes 🔸 Sets are unordered → Output order may change 🔸 |, &, -, ^ = shortcut operators 🔸 .update() type methods modify original set 🔸 Methods return new set (except update वाले) 🔸 Sets = fastest for uniqueness #Python #LearnPython #DataScience #Coding #Programming #PythonTips #Developers #SetsInPython #TechLearning
To view or add a comment, sign in
-
🐍 Python Practice day 5– Here are some problems I solved today: ✅ Find the frequency of elements in a list ✅ Convert a list into a tuple ✅ Find common elements between two sets ✅ Remove duplicates from a list using a set ✅ Find union and intersection of two sets ✅ Create a dictionary from two lists (keys and values) ✅ Count frequency of characters in a string using a dictionary ✅ Merge two dictionaries ----------------------------------Day ----------------- Find the frequency of elements in a list. try: list1=[1,11,1,22,11,1,33,4,5,66,77,66,4,5] frequency_count={} for i in list1: if i in frequency_count: frequency_count[i]=frequency_count[i]+1 else: frequency_count[i]=1 print(frequency_count) except ValueError: print("Error occured") ==Tuples, Sets, Dictionaries == Convert a list into a tuple. list1=[1,2,3,4] tuple1=tuple(list1) print(tuple1) Find common elements between two sets. set1={1,2,3,3,4,4} set2={1,2,4,7} print(set1.intersection(set2)) Remove duplicates from a list using set. list1=[11,11,1,1,1,1,2,3,3] set1=set(list1) print(set1) list1=[11,11,1,1,1,1,2,3,3] unique_list=[] for i in list1: if i not in unique_list: unique_list.append(i) print(unique_list) Find union and intersection of two sets. set1={1,2,3,4,} set2={4,5,6,7,1} union1=set1.union(set2) inter_sec=set1.intersection(set2) print(union1) print(inter_sec) Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1={} for i in range(len(keys1)): dict_1[keys1[i]]=values1[i] print(dict_1) # Create dictionary from two lists (keys and values) keys1=[1,2,3,4,5,6,7,8,9] values1=[9,8,7,6,5,4,3,2,1] dict_1=dict(zip(keys1,values1)) print(dict_1) Count frequency of characters in a string using dictionary. str1="DpkWtmVMwwids.MMpAMLPlz" dict1={} for i in str1: if i in dict1: dict1[i]=dict1[i]+1 else: dict1[i]=1 print(dict1) # Merge two dictionaries. dict1={"Name":"Deepak", "Subject":"DataScience" } dict2={ "Designation":"DataEngineer", "Salary":"Ye batein btayi ni jati" } dict1.update(dict2) print(dict1) Working through these problems again helped reinforce concepts like: • Iteration and loops • Dictionary operations • Set theory in Python • Clean and Pythonic approaches like zip() and built-in methods #Python #Learning #Programming #DataScienceJourney #CodingPractice
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development