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
Python Sets: Unique Data Collection & Math Operations
More Relevant Posts
-
🚀 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
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
-
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 with Machine Learning — Chapter 4 📘 Topic: Python Data Types 🔍 Let’s talk about Python Data Types. We’ll cover Indexing, Retrieval, and Slicing for: Lists, Dictionaries, Tuples, and Sets. Let’s dive in with one simple example! 👇 [CODE] # Python Data Types Overview # 1️⃣ Lists — Ordered, mutable my_list = [10, 20, 30, 40] print(my_list[0]) # Indexing: 10 print(my_list[1:3]) # Slicing: [20, 30] # 2️⃣ Dictionaries — Key-value pairs my_dict = {'name': 'Alex', 'score': 85} print(my_dict['name']) # Retrieval: Alex # 3️⃣ Tuples — Ordered, immutable my_tuple = (5, 10, 15) print(my_tuple[2]) # Indexing: 15 # 4️⃣ Sets — Unique, unordered my_set = {1, 2, 3} print(2 in my_set) # Retrieval: True [CODE] — 🌟 Quick Mentors Tips: Lists: Use indexing [0] and slicing [start:end] for ordered data. Dictionaries: Retrieve values using keys, like my_dict['key']. Tuples: Index like lists, but you can’t change them. Sets: Great for membership tests (in) and unique values. — You’ve got this! 💪 Practice these basics, and you’ll feel confident handling data. See you in Chapter 5! 🚀
To view or add a comment, sign in
-
PYTHON JOURNEY - Day 46 / 50..!! TOPIC – Python Modules Today I explored Modules — a way to organize code into separate files and use pre-written code from Python’s massive library. It’s like having a giant toolbox where you only pick the tools you need! 1. Importing Built-in Modules Python comes with many "batteries included" modules. To use them, we simply use the import keyword. Python import math print(math.sqrt(64)) # Output: 8.0 print(math.pi) # Output: 3.14159... 2. Using the random Module Perfect for games or selecting random data. Python import random options = ["Rock", "Paper", "Scissors"] print(random.choice(options)) # Picks a random item print(random.randint(1, 10)) # Random number between 1 and 10 3. Using alias and from You can give a module a nickname or import only a specific part of it to save memory. Python import datetime as dt from math import factorial print(dt.datetime.now()) print(factorial(5)) # Output: 120 Why Use Modules? Efficiency: Don't reinvent the wheel! Use proven code written by experts. Organization: Keep your project files clean by separating logic. Power: Modules allow Python to do everything from web scraping to Data Science and AI. Mini Task Write a program that: Imports the random module. Creates a list called players = ["Alice", "Bob", "Charlie", "David"]. Uses random.choice() to pick a random "Winner" from the list. Prints: "And the winner is... <name>! #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
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
-
-
🐍 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
-
-
🚀 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
-
-
GILs aren't just for fish. 🐟 Sometimes they're for snakes too. 🐍 Python's Global Interpreter Lock prevents parallelism. Python is slow. Python is single-threaded. So why does Python dominate big data? 🔻 Machine learning? PyTorch, TensorFlow (Python) 🔻 Data analysis? pandas, NumPy (Python) 🔻 Big data pipelines? PySpark, Dask (Python) This makes no sense! 😶🌫️ Big data demands massive parallelism, yet Python's GIL prevents exactly that. Here's the uncomfortable truth: Python doesn't process your data. NumPy, pandas, Polars, and PySpark do - and they don't have the GIL's limitations. When you write df.groupby('category').sum(), you're not running Python loops. You're calling optimized C/Rust code that releases the GIL and runs across all your CPU cores in parallel. 🗂️ What's inside: 🔹 How the GIL works (and why it exists) 🔹 The orchestration layer pattern 🔹 How NumPy, pandas, and Polars bypass the GIL 🔹 Fanout-on-write vs fanout-on-read strategies 🔹 When the GIL actually matters (and workarounds) 🔹 Python 3.13's experimental no-GIL mode The pattern is simple: Python coordinates. C/Rust/JVM executes. This isn't a workaround, it's architectural brilliance. 📚 Read the full article: https://lnkd.in/gWRuqg74 ❔ Have you encountered GIL-related performance issues in your Python projects? How did you solve them? ❔ #Python #DataEngineering #BigData #SoftwareEngineering #GIL #Performance #NumPy #Pandas #PySpark
To view or add a comment, sign in
-
#120 Days Challenge #Day-9 #Python In Python class, ma’am explained sets—an unordered collection of unique elements. We learnt methods like add, remove, discard, pop, clear, and operations such as union, intersection, difference, and symmetric_difference. #set-It's Methods set: A set is a collection of unique, unordered elements. Syntax: {element1, element2, …} or set(iterable) Duplicates are automatically removed. hashtag #Set Methods 1.Adding & Removing Elements: -->add(x) → Adds element x. -->remove(x) → Removes x (error if not present). -->discard(x) → Removes x (no error if not present). -->pop() → Removes and returns a random element. -->clear() → Removes all elements. 2. Set Operations: -->union() → Combines two sets. -->intersection() → Common elements. -->difference() → Elements in one set but not the other. -->symmetric_difference() → Elements in either set but not both. 3. Set Relations: -->issubset(other) → True if set is subset. -->issuperset(other) → True if set is superset. -->isdisjoint(other) → True if no common elements. 4. Others: -->copy() → Returns a copy of the set. -->len(set) → Number of elements in set. Pooja Chinthakayala Mam Saketh Kallepu Sir Uppugundla Sairam Sir Codegnan
To view or add a comment, sign in
More from this author
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