𝐍𝐮𝐦𝐏𝐲 𝐁𝐨𝐨𝐥𝐞𝐚𝐧 𝐓𝐫𝐚𝐩 I’m still at the very beginning of my Python journey. But even with my tiny amount of experience, I already hit a subtle NumPy trap that can easily sneak into real code. Python is full of surprises — even at the very beginning It happens when you create an untyped NumPy array and fill it with a function that should return booleans… …but sometimes returns 𝙉𝙤𝙣𝙚 when processing fails. At first, you expect a clean boolean array — because the function normally returns 𝙏𝙧𝙪𝙚 or 𝙁𝙖𝙡𝙨𝙚. But NumPy has other plans. Here’s the trap 👇 🟥 𝟏) 𝐔𝐧𝐭𝐲𝐩𝐞𝐝 𝐚𝐫𝐫𝐚𝐲 + 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐭𝐡𝐚𝐭 “𝐬𝐡𝐨𝐮𝐥𝐝” 𝐫𝐞𝐭𝐮𝐫𝐧 𝐛𝐨𝐨𝐥𝐞𝐚𝐧𝐬 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10) # 𝒏𝒐 𝒅𝒕𝒚𝒑𝒆 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() # 𝑻𝒓𝒖𝒆 / 𝑭𝒂𝒍𝒔𝒆 ... 𝒐𝒓 𝑵𝒐𝒏𝒆 You expect a clean boolean array because the function usually returns 𝙏𝙧𝙪𝙚/𝙁𝙖𝙡𝙨𝙚. But if even one value is 𝙉𝙤𝙣𝙚, NumPy must pick a type that can hold all values. 🟦 𝟐) 𝐍𝐮𝐦𝐏𝐲 𝐬𝐢𝐥𝐞𝐧𝐭𝐥𝐲 𝐬𝐰𝐢𝐭𝐜𝐡𝐞𝐬 𝐭𝐨 𝐝𝐭𝐲𝐩𝐞=𝐨𝐛𝐣𝐞𝐜𝐭 𝒂𝒓𝒓𝒂𝒚([𝑻𝒓𝒖𝒆, 𝑭𝒂𝒍𝒔𝒆, 𝑵𝒐𝒏𝒆, ...], 𝒅𝒕𝒚𝒑𝒆=𝒐𝒃𝒋𝒆𝒄𝒕) Impact: no vectorization logical operations break masks behave unpredictably performance collapses You think you have a NumPy boolean array. You actually have a Python object array. 🟩 𝟑) 𝐓𝐡𝐞 𝐬𝐢𝐥𝐞𝐧𝐭 𝐜𝐨𝐧𝐯𝐞𝐫𝐬𝐢𝐨𝐧 𝐭𝐫𝐚𝐩 Trying to fix it: 𝒂𝒓𝒓 = 𝒏𝒑.𝒆𝒎𝒑𝒕𝒚(10, 𝒅𝒕𝒚𝒑𝒆=𝒃𝒐𝒐𝒍) 𝒂𝒓𝒓[𝒊] = 𝒎𝒚_𝒇𝒖𝒏𝒄() NumPy converts: 𝑵𝒐𝒏𝒆 → 𝑭𝒂𝒍𝒔𝒆 (silently) Impact: 👉you lose the meaning of “no result” 👉your data becomes wrong 👉the bug becomes invisible ⭐ 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Same code. Same function. Two completely different arrays. NumPy’s dtype inference can hide subtle bugs — and I found this one with almost no Python experience. 𝐂𝐮𝐫𝐢𝐨𝐮𝐬 𝐭𝐨 𝐤𝐧𝐨𝐰: 👉 Have you ever run into this behavior? 👉 Or another NumPy dtype surprise? #python #numpy #datascience #cleanCode #devTips #programming
Romain Guillon’s Post
More Relevant Posts
-
Day 17 – Strings, Lists & Practical Logic Building in Python Today’s session was a mix of real-world logic building and deeper practice with strings and lists in Python. I started with a simple electricity bill calculation program using conditional statements. It helped me understand how tier-based logic works in real-life scenarios and how to structure conditions properly using if-elif-else. Strings – More Practice Revised and practiced important string methods: upper() and lower() for case conversion isupper() and islower() for validation capitalize() vs title() replace() with control over number of replacements This reinforced how strings are immutable and how every operation returns a new modified string. Lists – Slicing & Methods in Depth Worked extensively on list operations and understood the difference between modifying and non-modifying methods. Slicing Practice: Normal slicing Step slicing Reverse slicing Skipping elements using step values List Methods Explored: append() → add single element extend() → add multiple elements from iterable insert() → add element at specific index remove() → remove first occurrence pop() → remove by index (returns removed value) clear() → empty the list index() → find position of element sort() → modifies original list sorted() → returns new sorted list reverse() → reverse list order join() → join list elements into a string I also observed: How insert() behaves with negative and out-of-range indexes Difference between sort() and sorted() How extend() works differently with list, tuple, and set Key Takeaways Understanding method behavior is more important than just memorizing syntax Some methods modify the original list, others return new values Real learning happens when testing edge cases Logic building is improving step by step Day 17 was more about strengthening fundamentals and building clarity in how Python handles data structures. #Python #PythonLists #PythonStrings #ProgrammingBasics #DataStructures #CodingPractice #DailyLearning #ProblemSolving #LearnToCode #SoftwareDevelopment
To view or add a comment, sign in
-
I used to think strings were the “easy” part of Python… today proved me wrong. 🐍 Day 04 of my #30DaysOfPython journey was all about strings, and honestly, this topic felt way more powerful than I expected. A string is basically any data written as text — and it can be written using single quotes, double quotes, or triple quotes. Triple quotes also make multiline strings super easy. Today I explored: 1. len() to check length 2. Concatenation to join strings together 3. Escape sequences like \\n, \\t, \\\\, \\', \\" 4. Old style formatting with %s, %d, %f 5. New style formatting with {} 6. Indexing and unpacking characters 7. Reversing a string with str[::-1] And then came the string methods… that part felt like unlocking a toolbox: capitalize(), count(), startswith(), endswith(), find(), rfind(), format(), index(), rindex(), isalnum(), isalpha(), isdigit(), isnumeric(), isidentifier(), islower(), isupper(), join(), strip(), replace(), split(), title(), swapcase() What hit me today was this: strings are everywhere. Names, messages, input from users, file data, logs, even the little things we ignore at first. So yeah — not “just text.” More like one of the most important building blocks in programming. Github Link - https://lnkd.in/gUkeREkz What was the first Python topic that looked simple but turned out to have way more depth than expected? #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
Stop writing try/finally blocks. Use context managers instead. I see this pattern everywhere in Python codebases: connection = get_db_connection() try: result = connection.execute(query) finally: connection.close() Nothing wrong with it — until you have 15 resources to manage across your project. Here's the cleaner version with contextlib: from contextlib import contextmanager @contextmanager def db_connection(): conn = get_db_connection() try: yield conn finally: conn.close() with db_connection() as conn: result = conn.execute(query) Why this is better: → Resource cleanup logic lives in ONE place → You can't forget to close — it's automatic → Stack multiple with a single `with` statement → Works with async too (`@asynccontextmanager`) My favorite use case: temporary environment changes in tests. @contextmanager def override_settings(**kwargs): old = {k: getattr(settings, k) for k in kwargs} for k, v in kwargs.items(): setattr(settings, k, v) try: yield finally: for k, v in old.items(): setattr(settings, k, v) Small abstraction. Massive reduction in bugs. What's your favorite Python pattern that most people underuse? 👇 #Python #Programming #BackendDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
I just finished implementing 10 classical hypothesis tests from scratch in Python — no stats libraries, just numpy. Each test is built step by step, then verified against scipy.stats to confirm correctness: Welch's t-test (independent & paired) One-way ANOVA (Welch's) Chi-squared & Fisher's Exact Pearson & Spearman correlation Mann-Whitney U & Wilcoxon Signed-Rank Shapiro-Wilk normality test The goal wasn't to reinvent the wheel — it was to understand what's actually happening inside these black boxes. Each test comes with a visualisation: rejection regions on the test distribution, rank strip plots, Q-Q plots, residual heatmaps — all built to make the mechanics visible, not just the result. Code and full write-up on GitHub 👇 https://lnkd.in/d6JFnjE2
To view or add a comment, sign in
-
📘 Day 3 — Lists, If Conditions, For Loops… and Why Indentation Matters! Today’s learning felt like the moment Python started behaving like a real analysis tool. I covered: 🔹 Lists → storing multiple values 🔹 If Conditions → applying logic 🔹 For Loops → automating repetition 🔹 Indentation → the rule that makes everything work First — Lists Just like a column in Excel, Python lets us store multiple values together: marks = [65, 72, 58, 90, 48] Second — If Condition This allows Python to make decisions based on rules: if mark > 60: print("Pass") else: print("Fail") Third — For Loop Instead of checking each value manually, Python can go through the whole list: for mark in marks: if mark > 60: print("Pass") else: print("Fail") Now the Most Important Part — Indentation In many tools, spacing is just for readability. But in Python, indentation defines the structure of the code. Python uses indentation to understand: ✔ What belongs inside the loop ✔ What belongs inside the condition ✔ Where logic starts and ends Notice how everything inside the loop is indented: for mark in marks: if mark > 60: print("Pass") If indentation is wrong, Python throws an error — even if the logic is correct. So the key rule I learned today: 👉 Same logic block = Same indentation (usually 4 spaces) Today felt like moving from “writing code” to “teaching Python how to think through data.” #PythonLearning #DataAnalyticsJourney #codebasics #OnlineCredibility
To view or add a comment, sign in
-
-
Ever explained Duck Typing in Python to someone and watched their face go from 😃 → 🤯 in 3 seconds? Here’s how I tried explaining it to a friend: Friend: “How does Python know if something is a duck?” Me: Python doesn’t care if it’s a duck 🦆, a robot 🤖, or a developer pretending to work on Friday afternoon 😅 If it walks like a duck and quacks like a duck, Python just says: "Cool… must be a duck." Example 👇 class Duck: def quack(self): print("Quack!") class Person: def quack(self): print("I can imitate a duck!") def make_it_quack(obj): obj.quack() make_it_quack(Duck()) make_it_quack(Person()) Python: "Both quack? Perfect. I’m not asking for ID." Meanwhile in some other languages: "Excuse me sir, please submit 4 forms, 2 interfaces, and a type certificate before quacking." 🧾 That’s the beauty of Python — behavior matters more than type. So remember: In Python, nobody asks what you are. They only check what you can do. And honestly… that’s a life lesson too. 😄 #Python #DuckTyping #ProgrammingHumor #LearnToCode #PythonDeveloper #CodingLife #SoftwareEngineering #TechHumor #DeveloperLife
To view or add a comment, sign in
-
Day 18: Scope and Precision — The Limits of Logic 🌐 As your programs grow, you'll start having variables with the same names in different places. How does Python know which one to use? And when doing math, how many decimals can Python actually "remember"? 1. Local vs. Global Scope Think of Scope as the "area of visibility" for a variable. Global Scope: Variables defined at the top level (outside any function). They can be read from anywhere in your script. Local Scope: Variables defined inside a function. They only exist while that function is running. Once the function ends, the variable is deleted. 💡 The Engineering Lens: Avoid using too many Global variables. If every function can change a variable, it becomes a nightmare to track down bugs. Keep data "Local" whenever possible! 2. The LEGB Rule: Python’s Search Engine When you call a variable name, Python searches in a very specific order to find it. This is the LEGB rule: Local: Inside the current function. Enclosing: Inside any nested "parent" functions. Global: At the top level of the file. Built-in: Python’s pre-installed names (like len or print). 3. Precision: The Decimal Limit When you use a Float (a decimal number), Python has to fit that number into a fixed amount of memory. Maximum Precision: Python floats are typically "double-precision" (64-bit). This means they can hold about 15 to 17 significant decimal digits. The Default: When you perform a calculation, Python will show as many decimals as are relevant, but it stops being accurate after that 15–17 digit mark. 💡 The Engineering Lens: Because of this limit, 0.1 + 0.2 often equals 0.30000000000000004. If you are building a banking app or a scientific tool where you need infinite precision, don't use floats! Use Python’s decimal module instead. #Python #SoftwareEngineering #CleanCode #ProgrammingTips #DataPrecision #LearnToCode #TechCommunity #PythonDev
To view or add a comment, sign in
-
🐍 `__iter__()` & `__next__()` — How Python Loops Actually Work ******************************* Every time a `for` loop runs in Python, two methods run silently behind it. The distinction worth understanding: 1️⃣ An iterable has `__iter__()` — it can be looped over. 2️⃣ An iterator has both `__iter__()` and `__next__()` — it tracks position. Every list, string, file, and dict you loop over follows exactly this two-method protocol. ——————————————————————— When you implement it yourself, your objects become first-class citizens of the Python ecosystem — compatible with `for`, `list()`, `sum()`, `zip()`, and everything else. The real power is lazy evaluation. An iterator yields one value at a time. It does not load everything into memory upfront. That distinction becomes significant when the data is large. The visual guide below shows how both methods work, what a `for` loop actually does under the hood, and a real-world lazy CSV reader that handles large files without loading them into RAM. This series has covered `__init__()`, `__call__()`, `__enter__()` / `__exit__()`, `__del__()`, and `__str__()` / `__repr__()` — this one reveals the engine behind every loop you write. Next in the series → `__getitem__()` and `__setitem__()` Have you ever built a custom iterator? What was the use case? #Python #SoftwareEngineering #PythonDevelopment #sourcescodedev
To view or add a comment, sign in
-
-
Day 24: Iterators — The Engine Behind the Loop ⚙️ In Python, we often talk about "looping over data." But how does Python actually keep track of where it is in a list of 1 million items? It uses the Iterator Protocol. 1. Iterable vs. Iterator (The "Book" vs. The "Bookmark") Iterable: Any object you can loop over (List, String, Dictionary). Think of it as a Book. It contains all the data, but it doesn't "know" which page you are on. Iterator: A special object that represents a stream of data. Think of it as a Bookmark. It knows exactly where you are and what comes next. 2. The Tools: iter() and next() You can turn any Iterable into an Iterator using these two built-in functions: iter(my_list): Creates the "Bookmark" for that list. next(my_iterator): Moves the bookmark to the next "page" and returns the value. numbers = [10, 20] my_iter = iter(numbers) print(next(my_iter)) # Output: 10 print(next(my_iter)) # Output: 20 # print(next(my_iter)) # Error: StopIteration (The book is finished!) 3. Does it store data in memory? 🧠 This is the "Senior Engineer" secret. Lists/Tuples store all their data in memory at once. If you have 1 billion numbers, your RAM will crash. Iterators (and specifically Generators) are "Lazy." They don't store the whole list; they only calculate or fetch the next item when you ask for it. 💡 The Engineering Lens: This is why we use Iterators for massive datasets (like reading a 10GB log file). We process one line at a time, keeping our memory usage near zero! 4. The StopIteration Exception When an iterator runs out of items, it doesn't return None or 0. It raises a StopIteration error. 💡 The Engineering Lens: A for loop is actually just a "Fancy While Loop" that calls next() repeatedly and automatically handles the StopIteration error so your program doesn't crash. #Python #SoftwareEngineering #ComputerScience #MemoryManagement #Iterators #LearnToCode #CodingTips #TechCommunity #BackendDevelopment
To view or add a comment, sign in
-
𝗦𝘁𝗼𝗽 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻 𝗟𝗶𝗸𝗲 𝗮 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿 — 𝗗𝗼 𝗧𝗵𝗶𝘀 𝗜𝗻𝘀𝘁𝗲𝗮𝗱 I see this in code frequently. 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘄𝗵𝗼 𝗸𝗻𝗼𝘄 𝗣𝘆𝘁𝗵𝗼𝗻 𝗯𝘂𝘁 𝗮𝗿𝗲𝗻'𝘁 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻𝗶𝗰 𝗰𝗼𝗱𝗲. There's a difference between code that works and code that belongs in Python. Look at the two examples in the image. 𝗦𝗮𝗺𝗲 𝗼𝘂𝘁𝗽𝘂𝘁. 𝗕𝘂𝘁 𝗼𝗻𝗲 𝗿𝗲𝗮𝗱𝘀 𝗹𝗶𝗸𝗲 𝗮 𝘁𝗿𝗮𝗻𝘀𝗹𝗮𝘁𝗲𝗱 𝗖 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. The other reads like Python. Here are the patterns I see developers overuse and what to do instead: ❌ Manual index loops → ✅ enumerate() ❌ Building lists with .append() in loops → ✅ list comprehensions ❌ Checking "if len(x) > 0" → ✅ just "if x" ❌ Manual min/max logic → ✅ built-in min(), max() with key= ❌ Catching bare Exception → ✅ catch specific exceptions 𝗡𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 𝗮𝗿𝗲 𝗮𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗣𝘆𝘁𝗵𝗼𝗻. They're just Python being Python. When I started, I wrote Python like I was still thinking in C. It took real project work like building actual APIs and handling real data before these patterns became instinct. The shift happens when you stop learning syntax and start reading great Python code written by others. 𝗪𝗵𝗶𝗰𝗵 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 '𝗯𝗲𝗴𝗶𝗻𝗻𝗲𝗿 𝘁𝗿𝗮𝗽𝘀' 𝗱𝗶𝗱 𝘆𝗼𝘂 𝗳𝗮𝗹𝗹 𝗶𝗻𝘁𝗼 𝘁𝗵𝗲 𝗹𝗼𝗻𝗴𝗲𝘀𝘁 𝗯𝗲𝗳𝗼𝗿𝗲 𝗳𝗶𝗻𝗮𝗹𝗹𝘆 𝗯𝗿𝗲𝗮𝗸𝗶𝗻𝗴 𝘁𝗵𝗲 𝗵𝗮𝗯𝗶𝘁? #Python #PythonTips #CleanCode #BackendDevelopment #LearnPython #SoftwareEngineering
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