🐍 `__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
Muhammad Almas khan’s Post
More Relevant Posts
-
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
-
I think dictionaries might be the first Python topic that actually feels like organizing real life. 🐍 Day 08 of my #30DaysOfPython journey was all about dictionaries, and this one felt especially useful because it is basically how Python stores meaningful information. A dictionary is an unordered, mutable key-value data type. You use a key to reach a value — simple, but powerful. Today I explored: 1. Creating dictionaries with dict() built-in function and {} 2. Storing different kinds of values like strings, numbers, lists, tuples, sets, and even another dictionary 3. Checking length with len() 4. Accessing values using key name in [] or get() method 5. Adding and modifying key-value pairs 6. Checking whether a key exists using in operator 7. Removing items with pop(key), popitem() (removes the last item), and del 8. Converting dictionary items with items() which returns a dict_item object that contains key-value pairs as tuples 9. Clearing a dictionary with clear() 10. Copying with copy() and avoids mutation 11. Getting all keys with keys() and values with values(). These will return views - dict_keys() and dict_values() What stood out to me today was how dictionaries make data feel searchable instead of just stored. That key-value structure makes them one of the most practical tools in Python when working with real information. One more day, one more topic, one more step toward thinking in Python instead of just reading Python. When did dictionaries finally stop feeling confusing for you — or are they still one of those topics that need a second look? Github Link - https://lnkd.in/ewzDyNyw #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
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
-
-
🧠 Python Concept: join() for Strings Stop using + in loops 😵💫 ❌ Traditional Way words = ["Python", "is", "awesome"] sentence = "" for word in words: sentence += word + " " print(sentence.strip()) ❌ Problem 👉 Slow 👉 Messy 👉 Hard to read ✅ Pythonic Way words = ["Python", "is", "awesome"] sentence = " ".join(words) print(sentence) 🧒 Simple Explanation Think of join() like a glue 🧴 ➡️ It connects all words ➡️ Uses a separator (" ") ➡️ Gives a clean result 💡 Why This Matters ✔ Much faster than + ✔ Cleaner code ✔ Used in real-world string processing ✔ Avoids unnecessary loops ⚡ Bonus Example data = ["2026", "03", "27"] date = "-".join(data) print(date) 👉 Output: 2026-03-27 🐍 Don’t build strings piece by piece 🐍 Join them smartly #Python #PythonTips #CleanCode #LearnPython #Programming #Join #DeveloperLife #100DaysOfCode
To view or add a comment, sign in
-
-
How & What Python Class objects Did you know every class in Python is actually an object created by the type metaclass? - When we write a simple class like: class MyClass: pass - Python internally does something similar to this: MyClass = type("MyClass", (), {}) ◽ Yes, that means classes themselves are objects created dynamically at runtime. - Understanding the internals ◽ When you create an instance: obj = MyClass() ◽ Python internally calls: type.call(MyClass) ◽ Which further triggers the following sequence: 1. __new__(cls) → Starts object creation 2. object.__new__(cls) → Allocates memory 3. __init__(self) → Initializes the object ◽ So the real flow looks like: type.call(cls) ↓ cls.new(cls) ↓ object.new(cls) ↓ cls.init(obj) - But here's where things get interesting... By overriding the __call__ method inside a custom metaclass, we can manipulate how objects are created. - Example idea: class CustomizedMetaClass(type): def call(cls, *args, **kwargs): print("Object creation intercepted") return "Manipulated Reference" Now every time the class is called, instead of returning a normal object, it can return anything we want. ◽ This means we can control: • Object creation • Class behavior • Validation logic • Singleton patterns • Framework-level abstractions ◽ This is exactly why metaclasses are used in frameworks like Django, SQLAlchemy, and ORMs. - Key Takeaways ◽ In Python, everything is an object (including classes) ◽ Classes are created using the type metaclass ◽ type.__call__() controls object instantiation ◽ Metaclasses allow deep customization of class behavior Understanding this concept unlocks the real power of Python's object model. Github repo - https://lnkd.in/gkcGcunj #Python #PythonProgramming #PythonInternals #MetaProgramming #Metaclass #AdvancedPython #BackendDevelopment #Programming #CodeNewbie #DataScience
To view or add a comment, sign in
-
Day 27 of My Python Full-Stack Journey 🐍 Today's challenge: Reverse the words in a sentence — without using .reverse() or .join() Sounds simple? It made me think differently about strings and loops. Here's the logic I built from scratch: python def reverse_words(sentence): words = [] word = "" for char in sentence: if char == " ": if word: words.append(word) word = "" else: word += char if word: words.append(word) # Rebuild sentence manually result = "" for i in range(len(words) - 1, -1, -1): result += words[i] if i != 0: result += " " return result print(reverse_words("Hello World from Python")) # Output: Python from World Hello Key takeaways from today: → Manual string parsing builds real intuition → Constraints force creativity — no shortcuts = deeper understanding → Every loop you write by hand teaches you what built-ins do under the hood 27 days in. Still going strong. 💪 What would YOU add to make this more efficient? #Python #100DaysOfCode #FullStack #PythonProgramming #CodingJourney #LearningInPublic #Day27
To view or add a comment, sign in
-
-
💡 Python Control Flow with "try/except", "continue", and "break" Here’s an interesting Python snippet that combines exception handling with loop control statements: x = 0 for i in range(5): try: if i == 1: raise ValueError if i == 3: continue if i == 4: break x += i except ValueError: x += 10 print(x) 🔎 Key concepts demonstrated in this example: • "raise ValueError" triggers an exception intentionally when "i == 1", which moves execution to the "except" block and adds 10 to "x". • "continue" skips the remaining code in the current iteration (so "x += i" is not executed when "i == 3"). • "break" terminates the loop completely when "i == 4". • The "try/except" block ensures the program continues running even when an exception occurs. 📊 Step-by-step result: - "i = 0" → "x = 0" - "i = 1" → exception → "x += 10" → "x = 10" - "i = 2" → "x += 2" → "x = 12" - "i = 3" → "continue" → no change - "i = 4" → "break" → loop stops ✅ Final output: 12 Understanding how exception handling interacts with loop control statements is a powerful skill when writing robust Python code. #Python #Programming #AI #DataScience #100DaysOfCode #Analytics #Instant #LearningInPublic
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
-
Today I explored some important concepts in NumPy, I learned 👇 1. Arrays NumPy arrays are lists of numbers used for fast mathematical operations. Example: Python import numpy as np arr = np.array([1, 2, 3]) 🔹 2. Broadcasting Broadcasting means applying one value to all elements in the array automatically. Example: Python np.array([1,2,3]) + 5 # → [6 7 8] 🔹 3. Axis Axis tells which direction an operation runs. axis=0 → column-wise axis=1 → row-wise Example: Python arr.sum(axis=0) 🔹 4. Slicing Slicing means cutting a part of an array. Example: Python arr = np.array([10,20,30,40]) arr[1:3] # → [20 30] 🔹 5. Stacking Stacking means joining arrays. Example: Python np.hstack((a, b)) np.vstack((a, b)) 🔹 6. Random Values NumPy can create random numbers easily. Example: Python np.random.rand(2,3) 🔹 7. Reshape Reshape changes the shape of an array without changing data. Example: Python np.arange(6).reshape(2,3) # → [[0 1 2] # [3 4 5]]
To view or add a comment, sign in
More from this author
-
🧩 Starting a .NET Application from Scratch in 2026 — The “No-Regret” Checklist 💯
Muhammad Almas khan 4mo -
Mastering Database Objects: Stored Procedures, Functions, and Views for Optimal Performance
Muhammad Almas khan 5mo -
🚀 .NET 10: The Performance Beast — How NativeAOT + DATAS Made My Services Run Like Rocket Fuel
Muhammad Almas khan 5mo
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