The sorted() vs list.sort() explanation in most Python content is technically correct and practically useless. "sort() modifies in place, sorted() returns a new list" — yes, fine. But that framing makes it sound like a style preference. In a backend service it is not. list.sort() modifies the actual object in memory. Every other piece of code holding a reference to that object now sees changed data. A cache entry you didn't mean to touch. A parameter the caller expected to be unchanged. An audit log that should have preserved insertion order. None of this crashes. It just silently produces wrong output until someone notices. I wrote a longer piece on this because I also wanted to correct something: a lot of Python articles claim CPython drops the GIL mid-sort so other threads can see a partially sorted list. That's only true when you're using a Python lambda as the key. With no key function, the GIL stays held. The mutation after the sort is the problem regardless, but the claim itself is wrong and worth fixing. Link in the comments. #Python #PythonDeveloper #SoftwareEngineering
Python list.sort() vs sorted(): In-Place vs New List
More Relevant Posts
-
One Python feature I wish I started using earlier: **`dataclasses`**. When you’re building backend services, you often create “data-only” objects (DTOs, request/response models, internal payloads). Instead of writing repetitive boilerplate (`__init__`, `__repr__`, comparisons), you can do this: ```python from dataclasses import dataclass @dataclass(frozen=True, slots=True) class User: id: int name: str ``` Why I like it: - **Less boilerplate** → cleaner, more readable code - **`frozen=True`** → immutability (safer, fewer accidental changes) - **`slots=True`** → lower memory usage and often better performance Small change, big improvement—especially when your codebase grows. What’s one Python feature you wish you had used earlier? #Python #BackendDevelopment #SoftwareEngineering #CleanCode #Programming
To view or add a comment, sign in
-
Coming from Go, Python's type system felt loose to me at first. No compile step. No enforcement. Just... hints. But the more I dig in, the more I appreciate tools like `NewType` and `Literal`. In Go, the compiler stops you from mixing up types that share the same underlying type. Python can do something similar — not at runtime, but statically with Mypy. ```python from typing import NewType, Literal UserID = NewType("UserID", int) ProductID = NewType("ProductID", int) # Mypy catches this — both are ints, but they're not the same type process_order(ProductID(1), UserID(2)) # ❌ LogLevel = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] # Mypy catches this too set_log_level("WRONG") # ❌ ``` The discipline is on you to run the linter. But once you do, you get a surprisingly Go-like experience — catching swapped IDs and invalid strings before they ever hit production. Python's type system isn't weak. It's just opt-in. #Python #Go #TypeSafety #BackendEngineering #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 The Python Speed Stack 1. Optimize the Logic (The "Low Hanging Fruit") Before switching engines, check your oil. Built-ins: Use map(), filter(), and list comprehensions. They run at C-speed under the hood. Vectorization: If you are doing math in a for loop, you’re doing it wrong. Use NumPy or Pandas to push calculations into optimized C arrays. 2. The CPython Shortcuts Slots: Use __slots__ in your classes to prevent the creation of __dict__, saving memory and speeding up attribute access. Memshells: Use lru_cache from functools to avoid re-calculating expensive functions. 3. Change the Runtime If CPython is the bottleneck, swap the engine: PyPy: A JIT (Just-In-Time) compiler that can make long-running programs 5x–10x faster without changing a single line of code. Cython: Explicitly declare C types in your Python code. It compiles your .py into a C extension, giving you C-level performance while keeping Python syntax. 4. Parallelism vs. Concurrency I/O Bound? Use asyncio. It handles thousands of connections without the overhead of threads. CPU Bound? Use multiprocessing to bypass the GIL (Global Interpreter Lock) and utilize every core on your machine. 💡 The Golden Rule: Profile First Don't guess where the bottleneck is. Use cProfile or line_profiler to find the exact line slowing you down. Optimization without profiling is just organized guessing. What’s your go-to trick for speeding up a sluggish Python script? Let’s talk in the comments! 👇 #Python #SoftwareEngineering #Cython #ProgrammingTips #BackendDevelopment #DataScience #PerformanceOptimization #CodingLife
To view or add a comment, sign in
-
The Python "Gotcha" That Every Developer Hits Once Ever had a function return data from a previous call that you never asked for? You might be falling for the Mutable Default Argument trap. It’s a classic behavior that still catches experienced devs off guard. Take a look at the comparison below 👇 The Issue: Code 1 ❌ When you use a mutable object like a list or dict as a default argument, Python evaluates that expression only once — at the moment the function is defined. It doesn't create a new list for every call. Instead, it reuses the same object in memory. The result? Your data "leaks" from one function call to the next, creating a persistent state you probably didn't want. The Fix: Code 2 ✅ To ensure a clean slate every time, use the Late Binding pattern: Set the default value to None Initialize the mutable object inside the function body This ensures that a brand-new list or dictionary is created only when the function actually runs. ⚡ Key Takeaway Avoid using [], {}, or set() as default arguments. Stick to None or immutable types (strings, ints, tuples) to keep your code predictable and side-effect-free. It’s a small implementation detail, but mastering it saves hours of debugging "ghost data" in your backend. #Python #PythonDeveloper #Programming #SoftwareEngineering #BackendDevelopment #CodingTips #CleanCode #Debugging #ProgrammingTips #DevCommunity #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Python Pro-Tip: Stop using + to join strings. 🛑 If you’re building long strings or SQL queries with +, you’re hurting performance and readability. 📉 The Shortcut: f-Strings (Interpolation) ⚡ It’s faster, cleaner, and allows you to run code right inside the string. ❌ The Messy Way: url = "https://" + domain + "/" + path + "?id=" + str(user_id) ✅ The Clean Way: url = f"https://{domain}/{path}?id={user_id}" Why?? * Readability: It looks like the final result. * Performance: Python optimizes f-strings at runtime better than concatenation. * Power: You can even do math: f"Total: {price * 1.15:.2f}" Are you still using .format() or are you 100% on the f-string train? 👇 #Python #CleanCode #ProgrammingTips #SoftwareEngineering #BackendDev
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 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
-
Your build server is running out of space. You run df -h. 94% full. Great. So you du -sh your way through directories like it's 2005, mentally adding up numbers, until you finally find the 6 .venv folders nobody cleaned up. There's a better way — and building it yourself is half the point. In my latest article, I walk through building pydusk: a terminal disk usage analyzer in Python, inspired by ncdu. Keyboard-driven, non-blocking, with a delete confirmation flow and a clean TUI — all in a single file with two dependencies. Stack: Textual · Typer · os.scandir Things worth stealing from this project even if you never run it: → Why os.scandir beats os.walk for disk traversal → Textual's @work(thread=True) pattern for background tasks → ModalScreen[T] + dismiss() for confirmation dialogs https://lnkd.in/dmKvDSgH #Python #Textual #CLI #OpenSource #Developer
To view or add a comment, sign in
-
𝗬𝗼𝘂 𝗮𝗱𝗱𝗲𝗱 𝘁𝗵𝗿𝗲𝗮𝗱𝘀 𝘁𝗼 𝘀𝗽𝗲𝗲𝗱 𝘂𝗽 𝘆𝗼𝘂𝗿 𝗖𝗣𝗨-𝗯𝗼𝘂𝗻𝗱 𝗰𝗼𝗱𝗲. 𝗜𝘁 𝗴𝗼𝘁 𝘀𝗹𝗼𝘄𝗲𝗿. Don't blame Python. Blame the GIL (Global Interpreter Lock). The GIL ensures only one thread executes Python bytecode at a time. This is a safety feature, but for CPU-heavy tasks, it creates a bottleneck. Your threads aren't "working together"—they're fighting for the lock. The result? More overhead, zero speedup. The Rule of Thumb: 🔹 𝗜/𝗢-𝗯𝗼𝘂𝗻𝗱 (API calls, DB queries): Use 𝗧𝗵𝗿𝗲𝗮𝗱𝗣𝗼𝗼𝗹𝗘𝘅𝗲𝗰𝘂𝘁𝗼𝗿. Threads release the GIL while waiting for the network. 🔹 𝗖𝗣𝗨-𝗯𝗼𝘂𝗻𝗱 (Compression, Image processing): Use 𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗣𝗼𝗼𝗹𝗘𝘅𝗲𝗰𝘂𝘁𝗼𝗿. Each process gets its own Python instance and its own GIL. 🔹 Python 3.13 ships with an experimental no-GIL build — not production-ready, but the direction is clear Same interface, opposite internals. The decision is made at the Executor level — not scattered across your codebase #Python #SoftwareEngineering #BackendDevelopment #Concurrency #SoftwareArchitecture
To view or add a comment, sign in
-
-
Building a RAG app, primarily in Go. The pipeline is straightforward. Parse the PDF, create embeddings, upload to Postgres with pgvector, and use it for retrieval. Hit a wall with PDF parsing though. Go's support for it is nowhere close to what Python offers. So I split it, Python handles the parsing and writes the chunks to a file, and the Go ingest script picks it up from there and does the rest. Right tool for the right job. You don't have to go all in on one language for an entire pipeline. More on the tooling setup in the next post.
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
Full deep-dive article here: https://emitechlogic.com/why-sorted-is-safer-than-list-sort-in-production-python-systems/ Covers: • Silent mutation bugs in shared state • Real CPython memory behavior (PyListObject + ob_item) • Accurate GIL explanation (with & without key functions) • Production incident pattern walkthrough • When sorted() actually saves you debugging time • Decision framework + performance reality check Would love to hear your war stories with .sort() in prod — drop them below!