🚀 Day-9 — Sets in Python Sets are a powerful built-in data structure in Python used to store unique elements. They are especially useful when duplicate values must be automatically removed. 🔹 What is a Set? A set is a collection of items that is: ✔ Unordered ✔ Unindexed ✔ Mutable (can be changed) ✔ Stores only unique values Sets are defined using curly braces { }. 📝 Example: numbers = {1, 2, 3, 4, 4, 5} print(numbers) 📌 Output: {1, 2, 3, 4, 5} 🔹 Important Characteristics Duplicates are automatically removed No indexing or slicing (because sets are unordered) Elements must be immutable (int, str, tuple allowed; list not allowed) 🔹 Creating a Set set1 = {10, 20, 30} set2 = set([1, 2, 3, 4]) print(set1) print(set2) ⚠ Empty set: empty_set = set() # Correct empty_set = {} # ❌ This creates a dictionary 🔥 Adding & Removing Elements fruits = {"apple", "banana"} fruits.add("cherry") fruits.remove("banana") print(fruits) Other useful methods: discard() → removes element without error pop() → removes random element clear() → removes all elements 🔹 Set Operations Set operations are very useful for comparisons. ▶ Union a = {1, 2, 3} b = {3, 4, 5} print(a | b) ▶ Intersection print(a & b) ▶ Difference print(a - b) ▶ Symmetric Difference print(a ^ b) 🔹 Looping Through a Set for item in a: print(item) ⚠ Order is not guaranteed. ⚠ Common Beginner Mistakes ❌ Trying to access set elements using index ❌ Expecting order to remain same ❌ Confusing {} as empty set ❌ Adding mutable elements like lists 🌱 Best Practices Use sets when uniqueness matters Use set operations for fast comparisons Avoid relying on order of elements Sets are extremely efficient for handling unique values and comparisons. Once mastered, they simplify logic that would otherwise need complex loops. #Python #PythonProgramming #CodingJourney #LearnTogether #CodeDaily #ProgrammingBasics #TechCommunity
Mastering Python Sets for Efficient Data Management
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
Python with Machine Learning — Chapter 2 📘 Topic: Python Data Types 🔍 Let's keep building your foundation. Data types tell Python what kind of value you're working with. Mastering them helps you avoid bugs and write cleaner code. Here are 5 essential types we'll use in ML: 1. Integer — whole numbers → counts, indices, labels 2. Float — decimal numbers → prices, measurements, probabilities 3. String — text → names, messages, file paths 4. Boolean — True or False → conditions, decisions 5. None → missing values or placeholders [CODE] # Integers and Floats age = 25 pi = 3.14 # Strings name = "Alice" # Boolean is_active = True # None missing_value = None print(age, pi, name, is_active, missing_value) [/CODE] Methods and functions • String methods: name.lower(), name.upper(), name.strip() • Type conversion: int(), float(), str(), bool() Quick tips • Use type() to check a variable's type • Start simple and build confidence with small experiments You're doing great. Keep practicing. Next up: Lists
To view or add a comment, sign in
-
Build Your Own PDF RAG Agent: Python, Streamlit, ChromaDB, Neo4j & Groq RAG agents answer questions from your documents. Upload a PDF, ask questions, get answers with sources. This tutorial builds one from scratch. You’ll understand why each piece exists. How they connect. Where things can break. All the parts that tutorials usually skip. What RAG Actually Does: ——————————————— Normal chatbot: Guesses answers from training data. Gets things wrong. Makes up facts. RAG agent: Searches your documents first. Finds relevant sections. Uses those to answer. Cites sources. The difference is grounding. Answers come from real data, not imagination. The Four Components (How They Connect): 1. ChromaDB stores document chunks as vectors. Vectors are just number lists that represent meaning. “Dog” and “puppy” have similar vectors. “Dog” and “car” don’t. This lets you search by concept, not just keywords. 2. Neo4j tracks relationships between chunks. Chunk 5 connects to Chunk 6. Both mention “authentication.” When you retrieve Chunk 5, Neo4j knows Chunk 6 adds context. Grabs both. 3. Groq runs the LLM (Llama 3.3 70B). Takes your question plus retrieved chunks. Generates an answer. Does this fast — under 1 second. Free tier handles thousands of queries. 4. Streamlit builds the web interface. Python code becomes a working app. No HTML, CSS, or JavaScript needed. Each component handles one job. ChromaDB = storage and search. Neo4j = relationships. Groq = generation. Streamlit = UI. Clean separation makes debugging easy. Why This Stack ————————— Groq is fast. Other APIs take 3–5 seconds. Groq responds in under 1 second. Same model quality. Free tier is generous. ChromaDB runs locally. No server setup. No cloud costs. Just works. Data stays on your machine. Neo4j adds context. Vector search finds similar chunks. Graph search connects related chunks. Together they’re stronger than either alone. Streamlit ships fast. Write Python. Get web app. Deploy in minutes. #rag #ragagent #ai #aiagent #groq #neo4j https://lnkd.in/gqT3p9E9
To view or add a comment, sign in
-
🌟 Day 03 of Python-for-GenAI — Lists & Tuples Code • Read • Build Today’s focus was on something we use everywhere in real programs — collections. Most applications don’t deal with a single value. They deal with groups of values - items in a cart, user inputs, model outputs records that grow and shrink over time That’s where Lists and Tuples come in. 📌 What You Learn on Day 03 🔹 Lists – dynamic, editable collections 🔹 Tuples – fixed, reliable groupings 🔹 Indexing, adding, removing elements 🔹 When to modify data vs when to lock it Instead of just reading syntax, we apply it. 🛠 Hands-On Practice The hands-on exercises guide you to: Add items to a list Remove items safely Display structured output Understand how data changes step-by-step This builds the mindset needed for data handling, not just Python basics. 🚀 Mini Project: Grocery List Organizer (CLI) You build a menu-driven command-line application where users can: 1. Add item 2. Remove item 3. View list 4. Quit Behind the scenes: A list stores grocery items dynamically A tuple captures the first and last items safely The program responds to real user input Example output: Your Grocery List: - Apples - Bread Total items: 2 First & Last items: ('Apples', 'Bread') This project shows why lists are mutable and why tuples are perfect for fixed snapshots. Exactly how real programs behave. ⏱ Designed to be completed in ~1 hour Hands-on > theory. Always. 👉 Explore Day 03 (Notes + Hands-On + Mini Project): 🔗 https://lnkd.in/gY76NKH2 Building strong Python foundations — one real project at a time. #Python #GenAI #CodeReadBuild #LearningInPublic #DataStructures #Lists #Tuples #OpenSource #Day03 #CLIProject
To view or add a comment, sign in
-
-
🚀 From String Splits to Structured Data: A Quick Python Evolution Ever watched a simple Python script evolve? 😄 Started with extracting first names from a list: names = ["Charles Oladimeji", "Ken Collins"] fname = [] for i in names: fname.append(i.split()[0]) # Result: ['Charles', 'Ken'] Then flipped to last names: fname.append(i.split()[1]) # Result: ['Oladimeji', 'Collins'] Finally transformed it into clean, structured dictionaries: names = ["Charles Oladimeji", "Ken Collins", "John Smith"] fname = [] for i in names: parts = i.split() fname.append({"first": parts[0], "last": parts[1]}) # Result: [{'first': 'Charles', 'last': 'Oladimeji'}, ...] Why I love this progression: 1. Shows how small tweaks solve different problems 2. Demonstrates data structure thinking (list → list of dicts) 3. Real-world applicable for data cleaning/API responses 4. Sometimes the most satisfying code journeys start with a simple .split()! #DataEngineer #Python #Coding #DataTransformation #Programming
To view or add a comment, sign in
-
-
PYTHON JOURNEY - Day 45 / 50..!! TOPIC – Function Arguments (Default & Keyword) Today I dived deeper into Functions by learning how to make them more flexible using Default and Keyword arguments. This allows me to handle different scenarios without writing multiple functions! 1. Default Arguments You can assign a "default" value to a parameter. If the user doesn't provide a value, Python uses the default one. Python def greet(name, message="Welcome to the team!"): print(f"Hi {name}, {message}") greet("Srikanth") # Uses default message greet("Srikanth", "Let's build something cool!") # Overwrites default 2. Keyword Arguments When calling a function, you can specify the parameter names. This means the order of arguments doesn't matter anymore! Python def describe_pet(pet_name, animal_type): print(f"I have a {animal_type} named {pet_name}.") # Order doesn't matter if you use keywords describe_pet(animal_type="Dog", pet_name="Buddy") 3. Combining Both You can have a mix of required and optional parameters to create highly professional and reusable code. Why Use Advanced Arguments? Flexibility: Your functions can handle various inputs without crashing. Readability: Keyword arguments make it obvious what each value represents (e.g., price=500 is clearer than just 500). Scalability: Allows you to add new features to a function without breaking the existing code that calls it. Mini Task Write a program that: Defines a function make_bill(item, price, tax=0.05). The function should calculate the total price (price + price * tax). Call it once with just item and price. Call it a second time and provide a custom tax value (e.g., 0.10) using a keyword argument. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
To view or add a comment, sign in
-
-
Today’s Python focus was 𝗗𝗶𝗰𝘁𝗶𝗼𝗻𝗮𝗿𝗶𝗲𝘀 and 𝗧𝘂𝗽𝗹𝗲𝘀. I spent time understanding how Python handles structured data using key value pairs and fixed collections, and how this differs from lists. 𝗪𝗵𝗮𝘁 𝗜 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝗱 𝘁𝗼𝗱𝗮𝘆: • Creating dictionaries to store related data using meaningful keys • Accessing values using keys and using get() to avoid runtime errors • Updating existing values and adding new key value pairs • Deleting entries and checking for key existence • Iterating through dictionaries using keys and items() • Extracting only keys and only values when needed • Working with nested dictionaries to represent structured data • Iterating through nested dictionaries for multi level data • Using dictionaries to model real examples like contact details and revenue by region 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀: • Dictionaries store data as key value pairs, making lookups fast and clear • Dictionaries are mutable, so values can be updated without recreating the structure • get() is safer than direct key access when keys may not exist • Nested dictionaries are useful for representing hierarchical data • Iterating through dictionaries helps process structured datasets efficiently I also revisited 𝘁𝘂𝗽𝗹𝗲𝘀 conceptually and understood where they fit: • Tuples are ordered and immutable • They are useful when data should not change • Often used for fixed records, configuration values, or safe data grouping Working with dictionaries made it clear how real world data like contacts, configurations, and reports are represented in Python. If you are learning Python as well, which data structure are you currently focusing on? #Python #PythonLearning #DictionariesInPython #TuplesInPython #ProgrammingBasics #LearningInPublic #DataAnalytics #Upskilling
To view or add a comment, sign in
-
🐍 Python in 60 Seconds — Day 7 Numbers & Numeric Operations Python supports numbers naturally — no setup, no libraries. 🔢 Numeric types you’ll use most a = 10 → int b = 3.5 → float c = 2 + 3j → complex Most of the time, you’ll work with int and float. ➕ Basic math works as expected 5 + 2 → 7 5 - 2 → 3 5 * 2 → 10 But division has a twist 👇 ⚠️ Division surprise 5 / 2 → 2.5 Python always returns a float when dividing. You can even check it: type(5 / 2) → float If you want an integer result: 5 // 2 → 2 (floor division) 🔢 Remainder (very important) 5 % 2 → 1 Used in: • checking even / odd • cycles • conditions 🔺 Power 2 ** 3 → 8 🧠 Order matters (PEMDAS) 2 + 3 * 4 → 14 (2 + 3) * 4 → 20 Parentheses always win. 🔄 Mixing ints & floats 5 + 2.0 → 7.0 Python upgrades automatically. ⚠️ Beginner trap 0.1 + 0.2 → 0.30000000000000004 This is not a bug — it’s how computers store decimals. 🔙 Variables act like numbers Once a value is stored, Python treats the variable exactly like the number itself. x = 5 y = 3 z = x + y print(z) → 8 Python replaces x and y with their values, then performs the calculation. 🖨 Math inside print() You don’t need variables for every operation. You can do math directly inside print(): print(3 + 7) → 10 ⚠️ Important reminder about + The + operator depends on the data type: • With numbers → addition • With strings → joining Same symbol. Different meaning. 🔜There are more adbanced mathematical operations but they require an external library and it will be covered later. 💡 Insight Python is simple with numbers, but computers are not math professors — they’re approximators. 🔮 Next Strings and string operations — where text becomes powerful 😏🐍 #Python #LearnPython #Programming #Coding #TechCareers #DataScience #100DaysOfCode
To view or add a comment, sign in
-
-
📌 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 𝘃𝘀 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆 (𝗣𝘆𝘁𝗵𝗼𝗻) When copying objects in Python, many bugs happen because we assume all copies are independent - but they’re not. That’s where 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆 and 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 matter. 🔹 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆 A shallow copy creates a new outer object, but the inner (nested) objects are shared. • Outer object → new • Inner objects → same reference • Changes in nested data affect both copies 👉 Think of it as two folders pointing to the same files. 🔹 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 A deep copy creates a completely independent copy, including all nested objects. • Outer object → new • Inner objects → also new • Changes do NOT affect the original 👉 Think of it as duplicating both the folder and all files inside it. 🔹 𝗦𝗶𝗺𝗽𝗹𝗲 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original) deep = copy.deepcopy(original) shallow[0][0] = 99 • original → [[99, 2], [3, 4]] • shallow → [[99, 2], [3, 4]] • deep → [[1, 2], [3, 4]] 👉 Shallow copy shares inner objects, deep copy does not. 🔹 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗪𝗵𝗮𝘁 Use 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆 when: • Data is flat (no nesting) • Performance matters • Shared state is acceptable Use 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 when: • Data has nested structures • You need complete isolation • Safety is more important than speed 🎯 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗠𝗮𝘁𝘁𝗲𝗿𝘀 • Prevents unexpected bugs • Avoids side effects • Helps write predictable code 🔑 𝗦𝗶𝗺𝗽𝗹𝗲 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 👉 Shallow copy shares nested data. Deep copy duplicates everything. #Python
To view or add a comment, sign in
-
🐍 Python in 60 Seconds — Day 5 User Input & Typecasting This is where Python starts talking back to you 😄 🧑💻 Getting input from the user name = input("Enter your name: ") Let’s say the user types: World print("Hello", name) → Hello, World ⚠️ Important rule (memorise this) input() always returns a string even if numeric data is inputed . Example: x = input("Enter a number: ") print(x + x) Input: 5 Output: 55 ❗ Why? Because "5" + "5" is text joining, not math. 🔄 Typecasting (telling Python what you mean) Typecasting means converting one data type into another. To turn user input into numbers: age = int(input("Enter your age: ")) height = float(input("Enter your height: ")) Now Python knows these are numbers, not text. ➕ Now Python can do math print(age + 1) ✅ This works Because age is an int, not a string. ❌ Common beginner mistake age = input("Enter your age: ") print(age + 1) → Error 🚫 Python won’t guess what you want. You must be explicit. 💡 Insight Python is flexible — but not psychic 🧠 You decide what a value means. Consistency beats motivation. Next: Typecasting in depth #Python #LearnPython #Programming #Coding #TechCareers #DataScience #10DaysOfCode
To view or add a comment, sign in
-
Explore related topics
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