python

Coding Questions

Top 100 coding questions in Python

I have shared basic to advanced-level interview questions and answers. BASIC LEVEL (1-20) 1. Reverse a String 2. Check if a string is a palindrome 3. Find Factorial 4. Fibonacci Sequence 5. Check Prime Number 6. Find Maximum in List 7. Remove Duplicates from List 8. Count Character Frequency 9. Check Anagram 10. Find Missing Number in Array 11. Find Second Largest Number 12. Check Armstrong Number 13. Sum of Digits 14. Find GCD 15. Find LCM 16. Count Vowels in String 17. Check if String Contains Only Digits 18. Find Intersection of Two Lists 19. Find Union of Two Lists 20. Check Balanced Parentheses INTERMEDIATE LEVEL (21-60) 21. Two Sum Problem 22. Find Duplicates in Array 23. Move Zeros to End 24. Rotate Array 25. Find Majority Element 26. Binary Search 27. Merge Sorted Arrays 28. First Non-Repeating Character 29. Implement Stack using List 30. Implement Queue using List 31. Reverse Linked List 32. Detect Cycle in Linked List 33. Find Middle of Linked List 34. Implement Binary Tree 35. Tree Traversals 36. Maximum Depth of Binary Tree 37. Validate Binary Search Tree 38. Find All Permutations 39. Find All Subsets 40. Longest Substring Without Repeating Characters 41. Container With Most Water 42. 3Sum Problem 43. Merge Intervals 44. Find Peak Element 45. Search in Rotated Sorted Array 46. Word Break Problem 47. Longest Palindromic Substring 48. Implement LRU Cache 49. Find Kth Largest Element 50. Top K Frequent Elements ADVANCED LEVEL (51-80) 51. Serialize and Deserialize Binary Tree 52. Find Median from Data Stream 53. Regular Expression Matching 54. Wildcard Matching 55. Edit Distance 56. Coin Change Problem 57. Longest Increasing Subsequence 58. Maximum Subarray Sum (Kadane’s Algorithm) 59. House Robber 60. Climbing Stairs 61. Unique Paths 62. Decode Ways 63. Word Search 64. Number of Islands 65. Course Schedule (Cycle Detection) 66. Minimum Window Substring 67. Sliding Window Maximum 68. Trapping Rain Water 69. Largest Rectangle in Histogram 70. Merge K Sorted Lists 71. Sort Colors (Dutch National Flag) 72. Find First and Last Position 73. Spiral Matrix 74. Set Matrix Zeros 75. Valid Sudoku 76. N-Queens Problem 77. Sudoku Solver 78. Evaluate Reverse Polish Notation 79. Implement Trie (Prefix Tree) 80. Design Twitter ADVANCED ALGORITHMS & DATA STRUCTURES (81-100) 81. LFU Cache 82. Find Median in Two Sorted Arrays 83. Longest Consecutive Sequence 84. Alien Dictionary 85. Minimum Path Sum 86. Palindrome Partitioning 87. Reconstruct Itinerary 88. Minimum Height Trees 89. Word Ladder 90. Count of Smaller Numbers After Self 91. Maximal Rectangle 92. Burst Balloons 93. Serialize and Deserialize N-ary Tree 94. Flatten Nested List Iterator 95. Max Points on a Line 96. Word Search II 97. Candy Crush (1D) 98. Employee Free Time 99. Race Car 100. Swim in Rising Water

Top 100 coding questions in Python Read More »

How to Build Your Own AI Agent

In this blog, I’ll provide a short and clear explanation of how you can create your own AI agent.I’ll walk you through a comprehensive Python guide for building AI agents using the Microsoft Agent Framework. Building an AI agent is a large topic, but at a high level, it can be understood in a simple and practical way. What is an AI Agent: An AI agent is a system that observes its environment, reasons about what to do, and takes actions to accomplish tasks, often repeatedly and autonomously. Step-by-Step Python Guide 1. Installation 2. Prerequisites 3. Simple Agent Example Here’s a basic joke-telling agent: 4. Agent with Tools This example demonstrates how to add custom Python functions as tools that the agent can call: 5. Using Azure OpenAI This example shows how to create an agent using Azure OpenAI: 6. Agent with Conversation History Here’s how to create an agent that remembers previous interactions: 7. Key Concepts Agent Types Available Important Features 8. Next Steps Explore these advanced topics: 9. Official Resources

How to Build Your Own AI Agent Read More »

Master Python by Building 8 Classic Games

Learning Python by building games is one of the most effective ways to develop real programming skills. Each game teaches specific concepts while keeping you engaged and motivated. This roadmap will guide you from a beginner to a confident Python developer. Solutions will not be provided directly—you are encouraged to struggle, think, and build your own logic. This is where real learning happens. Avoid using AI to solve the problems; do it yourself to truly master Python. 1. Hangman What it teaches: String manipulation, lists, loops, basic I/O The game: Player guesses letters to reveal a hidden word. Each wrong guess adds a body part to the hangman. Six wrong guesses = game over. How to start: Key hint: Store the display as a list of characters, making it easy to reveal letters: [‘_’, ‘_’, ‘t’, ‘_’, ‘o’, ‘_’] 2. Rock Paper Scissors What it teaches: Random module, dictionaries for logic, game loops The game: Player picks rock, paper, or scissors. The computer picks randomly. Winner determined by classic rules. How to start: Key hint: Use a dictionary to encode what each choice beats instead of nested if-statements. This makes adding Lizard and Spock trivial. 3. Quiz Game What it teaches: Lists of dictionaries, file I/O, data organization The game: Present multiple-choice questions, track correct answers, show final score, and percentage. How to start: Key hint: Use a list of dictionaries to store questions. Later, read from a JSON file for easy question management. 4. Blackjack (21) What it teaches: Classes, complex state management, multiple functions The game: Get closer to 21 than the dealer without going over. Aces count as 1 or 11. Dealer hits to 16, stands on 17+. How to start: Key hint: Handle aces by starting them as 11, then converting to 1 if the hand busts. Use a function to calculate hand value. 5. Tic-Tac-Toe What it teaches: 2D lists, pattern checking, basic AI The game: Two players alternate placing X and O on a 3×3 grid. First to get three in a row wins. How to start: Key hint: Check win conditions by examining all rows, then all columns, then two diagonals. For AI, start with random moves, then add logic to block the opponent. 6. Mastermind What it teaches: Counting algorithms, feedback systems, careful logic The game: The computer picks a secret code of 4 colors. Player guesses, gets feedback on exact matches (right color, right position) and partial matches (right color, wrong position). How to start: Key hint: Calculate exact matches first, then count remaining colors that appear in both secret and guess for partial matches. 7. Dice Rolling Game (Yahtzee) What it teaches: Counter class, scoring logic, categorization The game: Roll 5 dice, choose which to keep, re-roll others (up to 3 rolls). Score based on combinations: three of a kind, full house, straight, etc. How to start: Key hint: Use collections.Counter to count dice values. Each scoring rule is a separate function that takes the dice list. 8. Battleship What it teaches: Multiple grids, coordinate systems, validation, and hidden information The game: Player and computer each place ships on a 10×10 grid. Take turns guessing coordinates to sink the opponent’s ships. How to start: Key hint: Use separate grids for the player’s board, the computer’s board, and tracking guesses. Convert input like “B4” to coordinates: row = ord(‘B’) – ord(‘A’), col = 3. Quick Start Guide Project Order Recommendation Beginner: Start with Hangman → Rock Paper Scissors → Quiz Game Intermediate: Tic-Tac-Toe → Mastermind → Blackjack Advanced: Dice Game → Battleship By the time you complete all eight games, you’ll have solid Python fundamentals and a portfolio of working projects. Now pick your first game and start coding!

Master Python by Building 8 Classic Games Read More »

Make Your Personal Blog Website with Wagtail CMS

So I’ve been wanting to build my own blog for a while now, and after trying out a bunch of different platforms like WordPress and some CMSs, I finally found Wagtail. And honestly? It’s been pretty great. Let me tell you why I think Wagtail is perfect for a personal blog and how you can get started with it. Why I Chose Wagtail I know what you’re thinking: “There are like a million blogging platforms out there—why Wagtail?” Fair question. Here’s the thing: I wanted something flexible enough to customize, but not so complicated that I’d spend weeks just setting it up. Wagtail is very easy to set up and customize with templates, but you still get the power and flexibility you need. And Wagtail is 10x faster than a WordPress website, and because it has much batter seo feature It’s built on Django, which I already have some experience with, and it provides a really clean admin interface that doesn’t feel like it was designed in 2005. Plus, it’s open source, which means no monthly fees eating into my coffee budget. What You’ll Need Before we dive in, here’s what you should have ready: Getting Started Alright, let’s actually build this thing. First, I recommend setting up a virtual environment because you don’t want to mess up your system Python packages. Now install Wagtail: Once that’s done, create your project: That last command will ask you to create an admin account. Don’t forget those credentials – you’ll need them to log into your admin panel. Now fire it up: Go to http://127.0.0.1:8000 And boom – you’ve got a Wagtail site running. The admin panel is at http://127.0.0.1:8000/admin. Setting Up Your Blog Here’s where it gets fun. Wagtail is all about creating custom page types. For a blog, you’ll want to create models for your blog index page and individual blog posts. Create a new app for your blog: Then add it to your INSTALLED_APPS settings file. In your blog/models.py, you’ll want something like this: Run migrations again: Creating Templates Wagtail needs templates to display your pages. Create a blog/templates/blog directory and add your templates there. Here’s a simple one for blog_page.html: Adding Some Style The default Wagtail setup is pretty bare-bones, which is actually good because you can style it however you want. I added some basic CSS to make mine look decent, and I’m planning to customize it more as I go. You can put your CSS in a static folder and link it in your base template. Nothing fancy is needed unless you want to get fancy. What I Like About This Setup After using this for my own blog, here’s what I appreciate: The admin interface is actually pleasant to use. I can draft posts, schedule them, and manage everything without wanting to throw my laptop out the window. The StreamField feature (which I didn’t cover here, but you should definitely look into) lets you create really flexible page layouts. And since it’s Django under the hood, I can add any custom functionality I want. A Few Gotchas It’s not all sunshine and rainbows, though. The learning curve is steeper than something like WordPress if you’re not familiar with Python or Django. And while the documentation is pretty good, sometimes you’ll need to dig around to figure out how to do something specific. Also, deployment is on you. Wagtail doesn’t come with hosting, so you’ll need to figure that out yourself. I ended up using a simple VPS, but there are easier options like PythonAnywhere or Heroku if you don’t want to deal with server management. Final Thoughts Building a blog with Wagtail has been a really good experience for me. It’s given me way more control than I’d get with a typical blogging platform, and I actually understand how everything works. If you’re comfortable with Python and want a blog that you can customize to your heart’s content, I’d definitely recommend giving Wagtail a shot.

Make Your Personal Blog Website with Wagtail CMS Read More »

9 Python Skills That’ll Get You Hired in 2026

The Python job market has changed—and fast. Companies don’t care how many certificates you’ve collected. They care about one thing only: can you build real, production-ready systems? If you’re serious about getting hired in 2026, these are the Python skills that actually matter. 1. Building Production-Ready APIs (FastAPI & DRF) Forget outdated Flask tutorials. Modern companies expect you to: Bonus points if you understand: If you can do this well, you’re already ahead of most applicants. 2. Data Engineering & Scalable Data Pipelines Everyone learned pandas during the pandemic. Now companies need engineers who can move and transform data at scale. Key skills: This is one of the fastest-growing Python career paths right now. 3. Applied AI & LLM Integration You don’t need a PhD to work in AI. If you can: …you’re extremely valuable. Companies don’t need AI theory—they need AI products that ship. 4. Docker, CI/CD & Production Deployment Code that only works on your laptop doesn’t count. You should know: This is what separates hobby projects from real systems. 5. SQL, Databases & Caching Not glamorous—but incredibly powerful. Many Python developers can’t write a proper JOIN. You should be comfortable with: Mastering databases alone can double your value. 6. Testing, Linting & Code Quality Companies are done with “it works on my machine.” Professional Python means: Boring? Maybe.But this is what pros do. 7. Cloud Fundamentals (Pick One and Go Deep) You don’t need to master every cloud. Pick one: Serverless tools like Zappa or Chalice are big bonuses. 8. Async Python & Performance Optimization Speed matters. You should understand: Developers who make systems faster are always in demand. 9. Data Visualization & Developer Demos Stakeholders love visuals. Beyond pandas, learn: Clear visuals turn engineers into decision-makers. Quick Start Paths (Choose One) If you’re starting, don’t overthink it: Pick a path.Build something real.That’s how you get hired in 2026

9 Python Skills That’ll Get You Hired in 2026 Read More »

10 Python Libraries That Build Dashboards in Minutes

Let me tell you something—I’ve wasted countless hours building dashboards from scratch, wrestling with JavaScript frameworks, and questioning my life choices. Then I discovered these Python libraries, and honestly? My life got so much easier. If you’re a data person who just wants to visualize your work without becoming a full-stack developer, this post is for you. 1. Streamlit I’ll be honest—Streamlit changed everything for me. You literally write Python scripts and get beautiful web apps. No HTML, no CSS, no JavaScript headaches. That’s it. That’s the tweet. Three lines and you’ve got an interactive dashboard. It’s perfect for quick prototypes and sharing models with non-technical stakeholders who just want to click buttons and see results. 2. Dash by Plotly When I need something more production-ready, I reach for Dash. It’s built on top of Flask, Plotly, and React, but you don’t need to know any of that. You just write Python and get gorgeous, interactive dashboards. The learning curve is slightly steeper than Streamlit, but the customization options are incredible. I’ve built entire analytics platforms with this thing. 3. Panel Panel is my go-to when I’m already working in Jupyter notebooks and don’t want to rewrite everything. It works seamlessly with practically any visualization library you’re already using—matplotlib, bokeh, plotly, you name it. What I love is that I can develop right in my notebook and then deploy it as a standalone app. No context switching, no rewriting code. 4. Gradio If you’re doing anything with machine learning models, Gradio is a gift from the tech gods. I’ve used it to demo models to clients, and the “wow factor” is real. You can wrap your model in a UI with literally 3 lines of code. Image classification? Text generation? Audio processing? Gradio handles it all and makes you look like a wizard. 5. Voilà Sometimes I just want to turn my Jupyter notebook into a dashboard without changing a single line of code. That’s where Voilà comes in. It renders your notebook as a standalone web app, hiding all the code cells. I use this all the time for presenting analysis to my team. They get to see the results and interact with widgets, but they don’t have to wade through my messy code. 6. Plotly Express Okay, technically Plotly Express isn’t a dashboard library—it’s a visualization library. But hear me out. The charts it creates are so interactive and beautiful that sometimes you don’t even need a full dashboard framework. I’ve literally built entire reports with just Plotly Express charts embedded in simple HTML. One-liners that create publication-ready visualizations? Yes please. 7. Bokeh Bokeh is for when I need fine-grained control but still want everything in Python. It’s great for creating custom interactive visualizations that feel professional and polished. The server component lets you build full applications, and I’ve used it for real-time monitoring dashboards. It handles streaming data beautifully. 8. Taipy I only recently discovered Taipy, but I’m kicking myself for not finding it sooner. It’s designed specifically for data scientists who need to build production applications. What sets it apart is how it handles scenarios and pipelines. If your dashboard needs to run complex workflows or manage different data scenarios, Taipy makes it surprisingly straightforward. 9. Solara Solara is all about reactive programming—your dashboard automatically updates when your data changes. It’s built on top of React but you never touch JavaScript. I love using this for dashboards that need to feel really responsive and modern. The component-based approach makes it easy to build complex interfaces without losing your mind. 10. Shiny for Python If you’re coming from the R world, as I did, Shiny for Python will feel like coming home. It brings the reactive programming model of R Shiny to Python, and it works beautifully. I appreciate how it encourages you to think about reactivity and state management from the start. The resulting dashboards feel polished and professional. My Honest Take Here’s what I’ve learned after building dashboards with all of these: there’s no “best” library. It depends on what you’re trying to do. The beautiful thing is that they’re all Python. You don’t need to become a web developer to build impressive, interactive dashboards. You just need to know Python and have something interesting to show. So pick one, build something, and stop overthinking it. I spent way too long agonizing over which library to learn first. Just start with Streamlit, you’ll have something running in 10 minutes, and you can always learn the others later. Now go build something cool and show it off. The world needs more data people who can actually visualize their insights.

10 Python Libraries That Build Dashboards in Minutes Read More »

The SQL Question That Filters 70% of Candidates

The Interview Scenario You’re sitting in a technical interview, feeling confident. You’ve written hundreds of SQL queries, optimized databases, and can JOIN tables in your sleep. Then comes the question: “Given a sales table with sale_date, product_id, and amount, write a query to find the second highest sale amount for each product. If there’s only one sale amount for a product, return NULL.” Sounds simple, right? Yet 70% of candidates get this wrong. Let’s unpack why. The Table Structure Sample data: The Trap: Three Levels of Understanding Level 1: The Novice Attempt (30% of candidates) The junior developer reaches for what they know: What’s wrong? This fails spectacularly with our sample data: Level 2: The Intermediate Attempt (40% of candidates) The mid-level engineer recognizes the need for distinct handling: Closer but still wrong: With amounts 200, 200, 150, DENSE_RANK gives 200→rank1, 150→rank2. That works! But wait… with amounts 200, 200, 200, DENSE_RANK gives all rank1, so no row with rank2. Returns nothing when it should return NULL. Plus, if we have 200, 200, 150, 150, we get TWO rows with rank2! Level 3: The Expert Solution (30% of candidates) The senior engineer thinks through all edge cases: Or more elegantly: The Four Critical Insights 1. Distinct Amounts First The phrase “second-highest amount” implies we’re talking about distinct values. Amounts 200, 200, 150 have two distinct amounts: 200 and 150. The second highest is 150. 2. NULL Means NULL, Not Empty The requirement “return NULL” means the result set should have a row for every product, with NULL in the amount column when there’s no second-highest. Most solutions that filter with WHERE drnk = 2 eliminate products. 3. DENSE_RANK vs RANK vs ROW_NUMBER 4. The GROUP BY Trick Using MAX(CASE…) with GROUP BY product_id ensures we get one row per product, with NULL where no second-highest exists. The Ultimate Solution Here’s the most robust version that handles all edge cases: What This Question Really Tests Practice Variations Master this pattern with these variations: The Takeaway This question isn’t about trickery—it’s about demonstrating you understand SQL at a deep level. The 70% failure rate reveals how many developers use SQL without fully understanding its semantics. Next time you write a window function, ask yourself: The best SQL developers don’t just write queries—they understand how data flows through them.

The SQL Question That Filters 70% of Candidates Read More »

If You Could Make Python Run 20× Faster Without Changing Your Logic?

If You Could Make Python Run 20× Faster Without Changing Your Logic?

Look, I love Python. I really do. It’s elegant, readable, and honestly? It just makes sense. But let’s be real for a second—it’s also slow. Like, painfully slow sometimes. I remember this one time I was processing a massive CSV file for a data analysis project. My script was chugging along, and I literally had time to make coffee, check my emails, and question all my life choices before it finished. I thought, “There’s got to be a better way, right?” Turns out, there is. And no, I’m not talking about rewriting everything in C++ or learning Rust (though props to you if you do). I’m talking about squeezing serious performance gains out of Python without touching your actual logic. Sounds too good to be true? Stick with me. The Reality Check Nobody Talks About Here’s the thing most tutorials won’t tell you: Python is an interpreted language, and that’s both its blessing and its curse. The same flexibility that makes it so easy to write also makes it… well, not exactly a speed demon. But before you start panicking and thinking you need to rewrite your entire codebase, let me share what I’ve learned from years of making slow Python code fast. The Low-Hanging Fruit (That Actually Works) 1. NumPy: Your New Best Friend If you’re doing anything with numbers—and I mean anything—and you’re not using NumPy, we need to talk. Seriously. I once rewrote a loop that was processing temperature data. The original version with regular Python lists took about 45 seconds. The NumPy version? Less than 2 seconds. Same logic, same result, just vectorized operations instead of loops. It’s almost embarrassing how much faster this is. 2. List Comprehensions Over Loops This one’s subtle but powerful. Python’s list comprehensions aren’t just more Pythonic—they’re actually faster because they’re optimized at the C level. The performance difference grows with your data size. And honestly? The comprehension version just looks cleaner too. 3. Use the Right Data Structure (Please) I spent weeks once debugging a performance issue that turned out to be… wait for it… using a list when I should’ve used a set. Checking if an item exists in a list is O(n). In a set? O(1). If I had a time machine, I’d go back and slap myself for not knowing this sooner. The Game Changers Codon: The Actual Game Changer Okay, this is where my mind was genuinely blown. Have you heard of Codon? It’s a Python compiler—not an interpreter, a compiler—that converts Python to native machine code. And get this: it can give you performance that’s basically on par with C/C++. I was skeptical at first. Like, really skeptical. But then I tried it on a bioinformatics script I’d been working on. Standard Python took about 12 minutes to process a genomic dataset. With Codon? 38 seconds. I checked three times because I thought I’d broken something. Here’s the wild part—you can use Codon’s JIT decorator in your regular Python code: That’s it. One import, one decorator. The @jit decorator compiles that function to native machine code the first time it runs, and every subsequent call is blazing fast. I’m talking 50-100x speedups for computational loops. The beautiful part? It’s literally just Python. You’re not writing in some weird subset of the language or learning new syntax. You write normal Python, add @jit, and Codon does the heavy lifting. The catch? It’s still relatively new (MIT developed it), and while it supports most of Python’s standard library, some third-party packages might not work yet. But for computational tasks, data processing, or anything CPU-intensive, where you’re writing your own logic? This is the real deal. I’ve started sprinkling @jit decorators on my performance-critical functions, and it’s become my go-to solution before considering any major rewrites. Numba: Magic When You Need It Numba is wild. You literally just add a decorator to your function, and it compiles it to machine code. It’s especially amazing for numerical computations. That @jit decorator can give you 10-100x speedups depending on what you’re doing. It’s not magic—it’s a JIT compiler—but it feels like magic. The Honest Truth About Caching Okay, real talk: I used to think caching was for people who were bad at writing efficient code. I was wrong. So, so wrong. Python’s functools.lru_cache is ridiculously easy to use and can make recursive functions or repeated calculations blazing fast. Without caching, calculating fibonacci(35) takes forever. With caching? Instant. It’s one line of code for potentially massive gains. When to Actually Care About This Stuff Here’s my honest advice: don’t optimize prematurely. I’ve wasted hours optimizing code that ran once a week and took 3 seconds. That’s 3 seconds I’ll never get back, and probably 2 hours of optimization time I definitely won’t. But when you’re dealing with: Then yeah, these techniques are absolutely worth it. The Bottom Line Python doesn’t have to be slow. Sure, it’ll never beat C for raw speed, but you know what? Most of the time, we don’t need C-level performance. We need code that’s fast enough and still maintainable. I’ve seen 20x speedups from just: And the best part? My code still looks like Python. It’s still readable. I can still come back to it in six months and understand what’s happening. So yeah, if someone told past-me that I could make my Python code 20x faster without rewriting the logic, I would’ve called them a liar. But here we are. And honestly? It feels pretty good.

If You Could Make Python Run 20× Faster Without Changing Your Logic? Read More »

what is python

What is Python?

Python is a widely-used programming language that’s known for being beginner-friendly. Created by Guido van Rossum and first released in 1991, it has become one of the most popular languages in the world. Python is commonly used for: What can you do with Python? Why choose Python? Important things to know How Python syntax differs from other languages How do we define a function? Simple Class creation.

What is Python? Read More »

Global Interpreter Lock in Python

What is Global Interpreter Lock in Python?

Hey everyone! Today I want to talk about something that’s been bugging me for a while – the Global Interpreter Lock, or GIL as everyone calls it. If you’ve ever wondered why your multi-threaded Python program doesn’t run as fast as you expected, well, the GIL is probably the culprit. So What Exactly is This GIL Thing? Okay, so here’s the deal. The Global Interpreter Lock is basically a mutex (a lock) that protects access to Python objects. It prevents multiple threads from executing Python bytecode at the same time. Even if you have multiple CPU cores, only ONE thread can execute Python code at any given moment. Why Does Python Even Have This? When I first learned about the GIL, my immediate reaction was “Why would anyone design it this way?” But there’s actually a good reason behind it. Python uses reference counting for memory management. Every object keeps track of how many references point to it, and when that count hits zero, the memory gets freed. The problem is that this reference count needs to be protected from race conditions where two threads try to modify it simultaneously. The GIL was the simple solution – just make sure only one thread runs at a time, and boom, no race conditions. It made the CPython implementation simpler and actually made single-threaded programs faster because there’s less overhead. When Does the GIL Actually Slowdown Performance? Here’s where it gets interesting. The GIL is only a problem for CPU-bound tasks. If your program is doing heavy calculations, processing data, or anything that keeps the CPU busy, the GIL will throttle your performance because threads can’t run in parallel. But here’s the good news – if you’re doing I/O-bound work (reading files, making network requests, waiting for database queries), the GIL isn’t really an issue. That’s because when a thread is waiting for I/O, it releases the GIL so other threads can run. I’ve worked on web scrapers and API clients where threading worked perfectly fine because most of the time was spent waiting for responses, not actually processing data. How I Deal With the GIL When I need actual parallelism for CPU-intensive tasks, I use the multiprocessing module instead of threading. Each process gets its own Python interpreter and its own GIL, so they can truly run in parallel. The downside? Processes are heavier than threads, and you can’t share memory as easily. But when you need real parallel processing, it’s worth it. Is There Hope for a GIL-Free Future? There have been attempts to remove the GIL over the years, but it’s tricky. Removing it would require massive changes to CPython’s internals and could break many existing C extensions that depend on the GIL’s behavior. That said, there are Python implementations, such as Jython and IronPython, that don’t have a GIL at all. And lately, there’s been renewed interest in making CPython work without the GIL, so who knows what the future holds? My Final Thoughts The GIL is one of those things that seems annoying at first, but once you understand it, you learn to work with it. For most of my day-to-day Python programming, it’s honestly not a problem. And when it is, I’ve got workarounds. The key is knowing what kind of problem you’re solving. CPU-bound? Use multiprocessing. I/O-bound? Threading works great. Once you’ve got that down, the GIL becomes just another quirk of Python that you deal with.

What is Global Interpreter Lock in Python? Read More »

Scroll to Top