🚀 Day 19/60 – Iterators (Understand How Python Loops Work Internally ⚡) Yesterday you learned Decorators. Today, let’s go deeper into how Python actually loops 👇 🧠 What is an Iterator? An iterator is an object that lets you loop through data one item at a time. 👉 Implements __iter__() and __next__() 👉 Used behind every for loop 🔄 How for loop works internally numbers = [1, 2, 3] iterator = iter(numbers) print(next(iterator)) # 1 print(next(iterator)) # 2 print(next(iterator)) # 3 👉 StopIteration is raised at the end ⚡ Custom Iterator class CountUp: def __init__(self, max): self.max = max self.current = 1 def __iter__(self): return self def __next__(self): if self.current > self.max: raise StopIteration val = self.current self.current += 1 return val for num in CountUp(5): print(num) 🔍 Iterator vs Iterable 👉 Iterable → Object you can loop over (list, tuple, string) 👉 Iterator → Object that actually produces values 🔥 Why Iterators Matter? ✅ Memory efficient ✅ Lazy evaluation ✅ Core of generators ❌ Common Mistake Confusing iterable with iterator ❌ 👉 Not every iterable is an iterator 🔥 Pro Tip 👉 Use iter() to convert iterable → iterator 👉 Use next() to manually fetch values 🔥 Challenge for today 👉 Create a custom iterator 👉 That returns numbers from 1 to 3 👉 Use next() manually Comment “DONE” when finished ✅ Follow Adeel Sajjad to stay consistent for 60 days 🚀 #Python #PythonProgramming #LearnPython #Coding #Programming #Developer
Python Iterators: Understanding Loops Internally
More Relevant Posts
-
🚀 Day 4 of #14DaysOfPython 🐍 Today’s focus: Strings (Core Concepts) — working with text in Python. 💡 Easy way to understand strings: 🔹 Why strings? 👉 Almost every real-world program deals with text (names, inputs, data processing) 💡 Core Concepts (Logic First): 🔹 String Indexing & Slicing 👉 Access characters using position s[0] → first character s[-1] → last character s[start:end] → substring 🔹 String Traversal 👉 Loop through characters for loop → simple iteration while loop → more control 🔹 Built-in Methods 👉 Modify strings easily lower(), upper() → case change strip() → remove spaces replace() → replace characters 🔹 ASCII Basics 👉 Convert between characters and numbers ord('A') → 65 chr(65) → 'A' 🧠 Problems I practiced: Palindrome check Reverse a string Count vowels & consonants Remove spaces from a string ✨ Key takeaway: Strings are not just text — they are data you can manipulate step-by-step using logic. Day 4 done ✅ Moving to Day 5 💪 #HackerRank #Python #ProblemSolving #CodingJourney #Developer #LearningInPublic #codegnan
To view or add a comment, sign in
-
-
Day 14/365: Rotating a List by k Positions in Python 🔁📦 Today I worked on a classic array/list problem: rotating a list to the right by k positions without using built‑in shortcuts. The goal: Given a list l = [1, 2, 3, 4, 5] and k = 2, the output should be: [4, 5, 1, 2, 3] Here’s the logic I used: I run a loop k times, because I want to rotate the list to the right by k positions. In each rotation: I first store the last element: last = l[-1] Then I shift every element one step to the right: Starting from the end and moving backwards: for j in range(len(l)-1, 0, -1): I set l[j] = l[j-1] so each position takes the value from its previous index. After this loop, the first position l[0] is empty (logically), so I place the old last element there: l[0] = last After repeating this process k times, the list is rotated right by k positions. 💡 What I learned: How to manually rotate a list step by step, instead of relying on slicing tricks. How backward loops work in Python using range(start, stop, step) with a negative step. Why thinking in terms of “shifting” elements helps in many array/list problems (rotations, circular buffers, games, etc.). How repeating a simple transformation k times can solve problems without complex math. Next, I’d like to explore: Handling large k values efficiently (e.g., using k % len(l)). Rotating to the left instead of the right. Solving the same problem using slicing and comparing both approaches. Day 14 done ✅ 351 more to go. Got any other list/array transformation problems (like cyclic shifts, sliding windows, or in‑place rearrangements)? Drop them in the comments—I’d love to try them next. #100DaysOfCode #365DaysOfCode #Python #Lists #LogicBuilding #DataStructures #CodingJourney #LearnInPublic #AspiringDeveloper
To view or add a comment, sign in
-
-
Just wrote about something I kept running into in real backend work — using Enums instead of plain dictionaries for fixed states like booking status, event types, and error codes. Nothing fancy. Just a pattern that reduced silent bugs and made the code easier to read and refactor. Read here: https://lnkd.in/gnYwTtzU #Python #BackendDevelopment #SoftwareEngineering #PythonTips #CleanCode #APIDesign #PythonDeveloper #CodeQuality #Programming #TechArticle
To view or add a comment, sign in
-
🔤 DAY 2/30: I CAN NOW MANIPULATE TEXT LIKE A PRO Today I learned string methods in Python - functions that transform text. 📚 WHAT I LEARNED: • .strip() - remove extra spaces (clean user input) • .upper() / .lower() - change case instantly • String slicing - grab specific parts of text [start:end] • .replace() - swap words in seconds 🛠️ PROJECT: Username Validator A program that: 1. Takes any messy username input 2. Cleans it (removes spaces, fixes case) 3. Validates length (5-15 characters) 4. Tells you if it's available 💡 BIGGEST INSIGHT: String methods don't change the original - they create a NEW string. That's why you need to save them: `name = name.strip()` 🐛 BUG I FIXED: Forgot to save the cleaned string - kept getting original. Now I know: methods RETURN values, they don't modify in place. 📂 DAY 2 CODE: https://lnkd.in/gvg2Rh6N 28 days to go. Getting stronger every day. #Python #30DaysOfCode #CodingJourney #LearnToCode
To view or add a comment, sign in
-
🧠 Python Concept: strip(), lstrip(), rstrip() Clean your strings like a pro 😎 ❌ Problem text = " Hello Python " print(text) 👉 Output: " Hello Python " 😵💫 (extra spaces) ❌ Traditional Way text = " Hello Python " text = text.replace(" ", "") print(text) 👉 Removes ALL spaces ❌ (not correct) ✅ Pythonic Way text = " Hello Python " print(text.strip()) # both sides print(text.lstrip()) # left only print(text.rstrip()) # right only 🧒 Simple Explanation Think of it like cleaning dust 🧹 ➡️ strip() → clean both sides ➡️ lstrip() → clean left ➡️ rstrip() → clean right 💡 Why This Matters ✔ Clean user input ✔ Avoid bugs in comparisons ✔ Very useful in real-world apps ✔ Cleaner string handling ⚡ Bonus Example text = "---Python---" print(text.strip("-")) 👉 Output: "Python" 🐍 Clean data, clean code 🐍 Small functions, big impact #Python #PythonTips #CleanCode #LearnPython #Programming #DeveloperLife #100DaysOfCode
To view or add a comment, sign in
-
-
Clean code isn't clever. It's clear. 5 Python patterns every developer should know: 1️⃣ Flatten nested list: flat = [x for sub in nested for x in sub] 2️⃣ Merge dicts (Python 3.9+): merged = dict_a | dict_b 3️⃣ Most frequent item: max(set(lst), key=lst.count) 4️⃣ Swap variables: a, b = b, a 5️⃣ Read + strip file lines: lines = [l.strip() for l in open("file.txt")] --------------- These aren't tricks. They're idiomatic Python. When your code communicates intent: ✅ Reviews go faster ✅ Bugs surface sooner ✅ Onboarding is smoother Write for the developer reading it at 2am before a deployment. That developer is usually you. #Python #CleanCode #Programming #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
There is something very powerful in Python that you can unlock by implementing just 2 methods. __𝙡𝙚𝙣__ __𝙜𝙚𝙩𝙞𝙩𝙚𝙢__ For example, if you implement this: 𝗰𝗹𝗮𝘀𝘀 𝗗𝗲𝗰𝗸: 𝗱𝗲𝗳 __𝗶𝗻𝗶𝘁__(𝘀𝗲𝗹𝗳, 𝗰𝗮𝗿𝗱𝘀): 𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀 = 𝗰𝗮𝗿𝗱𝘀 𝗱𝗲𝗳 __𝗹𝗲𝗻__(𝘀𝗲𝗹𝗳): 𝗿𝗲𝘁𝘂𝗿𝗻 𝗹𝗲𝗻(𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀) 𝗱𝗲𝗳 __𝗴𝗲𝘁𝗶𝘁𝗲𝗺__(𝘀𝗲𝗹𝗳, 𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻): 𝗿𝗲𝘁𝘂𝗿𝗻 𝘀𝗲𝗹𝗳.𝗰𝗮𝗿𝗱𝘀[𝗽𝗼𝘀𝗶𝘁𝗶𝗼𝗻] Your object automatically supports: • 𝗹𝗲𝗻(𝘥𝘦𝘤𝘬) • 𝘥𝘦𝘤𝘬[0] • slicing → 𝘥𝘦𝘤𝘬[:3] • iteration → 𝗳𝗼𝗿 𝘤𝘢𝘳𝘥 𝗶𝗻 𝘥𝘦𝘤𝘬 • 𝗶𝗻 operator • 𝗿𝗮𝗻𝗱𝗼𝗺.𝗰𝗵𝗼𝗶𝗰𝗲(𝘥𝘦𝘤𝘬) • 𝘀𝗼𝗿𝘁𝗲𝗱(𝘥𝘦𝘤𝘬) You didn’t implement: • iteration • slicing • search • random selection Python gave you all of that. That takeaway is: If your object behaves like a sequence, Implement __𝗹𝗲𝗻__ + __𝗴𝗲𝘁𝗶𝘁𝗲𝗺__ and let Python do the rest. Don’t build features. Plug into the Data Model. #python #datamodel #dunder #magicmethods #__len__ #__getitem__
To view or add a comment, sign in
-
🚀 Level Up Your Python Code with collections.Counter 🐍 Still using manual loops and dictionaries to count items? There’s a smarter, cleaner way—meet Counter, a powerful subclass of Python’s built-in dict designed specifically for counting. Here’s why it deserves a spot in your toolkit 👇 🔹 Effortless Counting Just pass any iterable (list, string, tuple, etc.), and it automatically calculates frequencies. Keys are elements, values are their counts—simple and efficient. 🔹 No More KeyError Access a missing element? No crash. Counter returns 0 by default. 🔹 Supports Negative & Zero Counts Unlike regular counting logic, Counter handles zero and even negative values seamlessly. 🔹 Built-in Power Methods most_common(n) → Get top n frequent elements instantly update() & subtract() → Add or remove counts easily elements() → Expand back into elements based on counts 🔹 Multiset Operations Made Easy Perform arithmetic operations directly: + → Combine counts - → Subtract counts & → Intersection (minimum counts) | → Union (maximum counts) 💡 Why it matters? Cleaner code, fewer bugs, and faster development. No need to reinvent counting logic—Counter handles it elegantly. #Python #PythonCounter #PythonCollections #DataStructures #DataScience #PythonProgramming #DeveloperCommunity #CodingTips #LearnPython
To view or add a comment, sign in
-
-
Unlocking the Power of Strings in Python! 🐍✨ Today’s focus on my Python journey was all about understanding and manipulation—specifically, Strings. It’s incredible how much logic depends on effectively handling text data! Here are my key takeaways from today's deep dive: ✂️ String Slicing: Mastering the [start:stop:step] syntax. It feels like precision surgery for text data—extracting exactly what you need, whether it's a prefix, a suffix, or a reversed substring. 🚫 String Immutability (Mutation): A crucial realization! You can’t change a string in place. Trying to do word[0] = 'C' will throw an error. Understanding this forces you to think correctly about creating new modified strings instead of trying to mutate existing ones. 🛠️ String Methods: My toolbox just got a lot bigger. I explored powerful built-in functions like: .strip() for cleaning up whitespace. .replace() for quick swaps. .split() and .join() for converting between strings and lists. .upper(), .lower(), .capitalize() for formatting. Understanding these fundamentals is making my code cleaner and more efficient. Every day is a step closer to building complex applications! #Python #CodingJourney #Strings #DataManipulation #SoftwareDevelopment #ContinuousLearning #WebDev #Backend #ProgrammingFundamentals #CleanCode #LearningToCode
To view or add a comment, sign in
-
-
Python type checkers can catch more than type mismatches. To understand your code's types, a type checker also has to understand control flow, scoping, and class hierarchies, which means it can catch a surprisingly wide range of bugs. In this Pyrefly blog, Rebecca Chen walks through five surprising bug patterns, none are straightforward type errors, but Pyrefly catches them all ✨ https://lnkd.in/eyJpQ7uY #python #pyrefly
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