Why range(1,000,000) is cheap, but list(range(1,000,000)) is costly in Python? TL;DR: Iteration Protocol in Python needs to know only next item and not full list. The "Next Page" Rule Iteration in Python isn't about having a collection of items; it’s about knowing how to get the next item. Two special methods make this possible: 1. __iter__() → tells Python “I can be looped over” 2. __next__() → returns the next value, one at a time When there’s nothing left, StopIteration tells Python to stop the loop. Why this matters? When we use a list, we pay for all the memory upfront. When we use the Iteration Protocol, we only pay for one item at a time. This is called Lazy Evaluation. Takeaway - If the object represents a collection or a stream of data, implement __iter__ and __next__. It makes the code more memory-efficient and much more "Pythonic." I’m deep-diving into the Python protocols this week and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
Python Iteration Protocol: Lazy Evaluation with __iter__ and __next__
More Relevant Posts
-
🧠 “Interesting Python Nugget” (Lists) Python List Trick You’ll Actually Use Did you know you can remove duplicates from a list in ONE line? nums = [1, 2, 2, 3, 4, 4] unique_nums = list(set(nums)) ✔ Simple ✔ Fast ✔ Super handy for real projects Python has tons of these tiny gems that save time and make code cleaner. 📬 We explain one Python concept every day — short, clear, and practical. Want more? Subscribe and learn Python daily ✨ link in the comments Please sign up and follow #PythonChallenge #PythonLearning #CodeChallenge #PythonDaily #PyDaily
To view or add a comment, sign in
-
-
Why 60 * 60 * 24 costs the same as 86400 in Python? TL;DR: Python evaluates it once at compile time! You might think writing out the math makes the code slower because Python has to do the multiplication every time. When Python compiles source code into Bytecode, it uses an optimiser (Peephole) that looks for constants. This is called Constant Folding. It’s not just for numbers! Python also folds small strings. "Deep" + "Tech" becomes "DeepTech" in the bytecode. Takeaway: -> Never sacrifice readability for a "assumed" performance gain in constants. -> Python’s compiler is not just a translator, it’s an optimiser. -> Compiler handles the math smartly, so you can focus on writing code that humans can actually read! I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Tuples in Python: Immutable (cannot be changed after creation), ordered collection that allows duplicate elements. Syntax:() Two methods: Index(),count() Python 3.14.0 (tags/v3.14.0:ebf955d, Oct 7 2025, 10:15:03) [MSC v.1944 64 bit (AMD64)] on win32 Enter "help" below or click "Help" above for more information. >>> #tuples() >>> a=(4,5.7,"python",4+9j,True,False) >>> print(a) (4, 5.7, 'python', (4+9j), True, False) >>> type(a) <class 'tuple'> >>> len(a) 6 >>> a.count("python") 1 >>> a.index(True) 4 Pooja Chinthakayala Mam,Saketh Kallepu Sir,Uppugundla Sairam Sir
To view or add a comment, sign in
-
Why Python prefers 𝘵𝘳𝘺 / 𝘦𝘹𝘤𝘦𝘱𝘵 over 𝘪𝘧 𝘦𝘭𝘴𝘦 checks? TL;DR: In Python, exceptions are part of normal flow, not rare events! There are two ways to walk through a uncertain code block - 1. Look Before You Leap (LBYL) - - Check conditions before doing the action - The 𝘪𝘧 𝘦𝘭𝘴𝘦 statements. - But here, Python looks at the dictionary twice. Once to check if the key exists, and once to actually fetch it. 2. Easier to Ask Forgiveness than Permission (EAFP) - Assume things will work and wrap the action in a try block. - If the key exists (which is usually the case), execution stays on the fast path. EAFP is the "Pythonic" approach. It is the way Python is built internally too. Python uses exceptions internally for everything. When using a for loop, Python doesn't check the length of the list; it just keeps asking for items until the list raises a StopIteration exception. Takeaway - -> Using try excepts will not add to any extra processing time, if not reduce it in most of the practical cases. -> Use LBYL if the failure is expected to happen often. -> Use EAFP if the failure is unexpected and rare. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Day 26 | Python Tricks Beginners Don’t Know 🐍 When I started Python, I thought writing longer code meant better code. Turns out… smarter Python is often shorter. Here are a few simple tricks that changed how I write code: 1️⃣ Multiple Assignment Instead of: a = 5 b = 10 You can write: a, b = 5, 10 2️⃣ Swapping Variables (Without Temp Variable) Instead of: temp = a a = b b = temp Just write: a, b = b, a 3️⃣ Using enumerate() Instead of Manual Indexing Instead of: for i in range(len(items)): print(i, items[i]) Use: for index, value in enumerate(items): print(index, value) Cleaner. More readable. More Pythonic. Python isn’t about writing more code. It’s about writing clear, efficient code. Which Python trick surprised you when you learned it? #Day26 #PythonLearning #PythonTips #CodingJourney #AIJourney #DataScienceStudent #LearningInPublic #TechGrowth
To view or add a comment, sign in
-
Why .join() is faster than str1 + str2 in Python? Why string concatenation gets really slow in Python? Strings are immutable in Python. When we write str1 + str2, following steps are done - 1. Request a brand new block of memory large enough for both. 2. Copy every single character from str1 and str2 into the new block. 3. Destroy the old strings (eventually) If we do this 10,000 times in a loop, we are copying millions of characters over and over again. When we use ''.join(list_of_strings), Python is significantly smarter. It performs following 2 pass operation - 1. It iterates through the entire list once to calculate the total length of the final string. 2. it allocates one single block of memory of that exact size and copies all the strings into their respective slots at once. Instead of n reallocations and n copies, one allocation and one copy! Takeaway - -> Need to join 2 or 3 strings - a + b is fine and very readable. -> Need to join strings in a loop - Always collect them in a list first and use ''.join(my_list) at the very end. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
When I review Python code, I often look past syntax and focus on decisions. Take this line: if user_id in users: grant_access() It works. But what matters is what users actually is. A list → Python checks items one by one A set or dict → Python jumps straight to the answer Same line of code. Very different performance. With large data, these choices decide whether a system feels instant or slow. This is the kind of detail that separates: • someone who writes Python • from someone who understands how Python behaves I recently wrote a complete breakdown of how Python searches data internally—linear search, binary search, and hash lookup—using real examples and benchmarks. It’s not about algorithms. It’s about choosing the right data structure upfront. Full breakdown 👇 https://lnkd.in/gT2uaZER #Python #SoftwareEngineering #BackendEngineering #Performance #CodeQuality
To view or add a comment, sign in
-
-
How FINALLY keyword in Python can silently change your function’s behaviour? How does the try except flow works? 1. When Python enters a try block, it pushes a "cleanup" instruction onto the stack. 2. When you hit a return statement inside try, Python doesn't actually exit the function immediately, it just "saves" the return value. 3. If you return inside the finally block itself, the original return value is discarded. More worse - This same thing happens with exceptions too. If your try block raises a error, but your finally block has a return or a break, the error vanishes! Takeaway - 1. Never use return, break, or continue inside a finally block. It can lead to "silent failures" and unexpected bugs. 2. Finally is meant only for cleanup (closing files, releasing locks) and not logic. I’m deep-diving into Python internals. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Day 7: Python Full-Stack Journey 🐍 | Unpacking the Power of Packing & Unpacking Today I explored one of Python's elegant features that makes code cleaner and more intuitive—variable packing and unpacking! What I learned: Unpacking allows you to assign multiple values in one line, making code more readable. For example, instead of accessing list indices separately, you can extract values directly: python coordinates = (10, 20) x, y = coordinates The asterisk operator takes this further by collecting remaining values. This is especially useful when you only care about certain elements: python first, *middle, last = [1, 2, 3, 4, 5] # first = 1, middle = [2, 3, 4], last = 5 For function arguments, packing with *args and **kwargs provides incredible flexibility, allowing functions to accept variable numbers of arguments without defining each parameter explicitly. Real-world application: I built a simple function that processes API responses by unpacking nested data structures, making the code significantly more concise than traditional index-based access. The beauty of unpacking is how it transforms verbose code into something elegant and Pythonic. It's these small features that make Python feel intuitive. What Python feature has surprised you with its elegance? #Python #100DaysOfCode #FullStackDevelopment #LearnInPublic #WebDevelopment #Coding
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
List conversion requires a bulk of data to to be stored as a whole at a time. range is a generator function using which such large data can be fetched as a stream as per the need one at a time. So thats why memory requirements are lesser... Good posts..