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
Rotating a List by k Positions in Python
More Relevant Posts
-
🚀 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
To view or add a comment, sign in
-
-
🚀 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 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
-
I did not expect a Python topic about “unique items” to feel this useful… but sets changed that fast. 🐍 Day 7 of my #30DaysOfPython journey was all about sets, and this one felt different because it was less about storing data and more about controlling it. A set is an unordered collection of distinct items. It cannot hold duplicates, which makes it super handy in real-world coding. Today I explored: 1. Creating sets with set() built-in function and {} 2. Checking length with len() 3. Using in to check if an item exists 4. Adding items with add() to add a single item and update() for multiple items 5. Removing items with remove() (raise error if item not present), discard() (does not raise error), and pop() (removes a random item) 6. Clearing a set with clear() 7. Deleting a set with del 8. Converting a list to a set to remove duplicates 9. Set operations like union(), intersection(), difference(), and symmetric_difference() 10. Checking issubset(), issuperset(), and isdisjoint() What made sets interesting to me today was how practical they are when you want uniqueness, comparison, or clean data without duplicates. They may look simple on the surface, but they solve a very specific kind of problem really well. Which Python data type has surprised you the most so far: lists, tuples, or sets? Github Link - https://lnkd.in/eJfTX-HQ #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
🚀 Day 3/30 of My LeetCode Journey (Python + SQL) Showing up daily and building consistency, one problem at a time! 💻🔥 🔹 **Python Problems of the Day** 👉 *1. Move Zeroes* Given an integer array, move all 0’s to the end while maintaining the relative order of non-zero elements. Do it in-place without making a copy. 💡 *Key Concept:* Two-pointer technique for efficient in-place rearrangement. 👉 *2. Remove Element* Given an array and a value, remove all occurrences of that value in-place and return the number of remaining elements. 💡 *Key Concept:* In-place filtering using pointer overwrite approach. 🔹 **SQL Problem of the Day** 👉 *Find Duplicate Emails* Given a `Person` table with an email column, write a query to report all duplicate emails. 💡 *Key Concept:* GROUP BY with HAVING COUNT > 1. Small steps daily = Big progress over time 📈 Staying consistent and enjoying the process! #LeetCode #30DaysChallenge #Python #SQL #CodingJourney #Consistency #ProblemSolving #LearnInPublic
To view or add a comment, sign in
-
Day 11/365: Finding the Smallest & Second Smallest Element in a List 🔍📉 Today I worked on a classic list problem in Python: finding the smallest and second smallest elements in a list, along with their indexes — without sorting the list. What this code does step by step: I start with a list L containing different numbers. I initialize two variables: smallest and s_smallest (second smallest) with a value larger than most of the elements in the list. I also track their positions using smallest_index and second_smallest_index. Then I loop through the list using indexes: If the current element is less than or equal to smallest, I: move the current smallest to s_smallest, update smallest with the new value, and update both indexes accordingly. Else if the current element is only smaller than s_smallest, I update just the second smallest and its index. In the end, I print both the smallest and second smallest values with their positions in the list. What I learned from this exercise: How to track not just one, but two minimum values in a single pass through the list. How important it is to maintain both the value and the index while updating. How careful initialization of variables (like smallest and s_smallest) affects the correctness of the logic. How this pattern can be extended to find top-k smallest or largest elements efficiently without sorting. Day 11 done ✅ 354 more to go. If you have ideas like handling edge cases (e.g., duplicates, negative numbers, very large lists) or finding the k-th smallest element, send them my way — I’d love to build on this next. #100DaysOfCode #365DaysOfCode #Python #LogicBuilding #Lists #Indexing #CodingJourney #LearnInPublic #AspiringDeveloper
To view or add a comment, sign in
-
-
Day 2 of my LeetCode journey 🚀 Today’s problem: Group Anagrams This challenge was all about grouping strings that share the same characters. I approached it using a dictionary + hashing strategy in Python. For each word, I sorted its characters and used that as a key (converted into a tuple), ensuring all anagrams map to the same bucket. Here’s the core logic I implemented: ▪️Traverse the list of strings ▪️Sort each string → convert to tuple → use as dictionary key ▪️Append original string to the corresponding group ▪️Finally, return all grouped values This approach keeps the implementation clean and scalable. Time Complexity: ▪️Sorting each string takes O(k log k) (where k = length of string) ▪️For n strings → O(n * k log k) overall Space Complexity: ▪️O(n * k) for storing grouped anagrams A solid step forward in understanding how hashing + transformations can simplify complex grouping problems. Staying consistent and leveling up daily 💪 #LeetCode #Day2 #Python #DSA #CodingJourney #ProblemSolving
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
-
-
📅 Day 5 of Python — and today was all about putting knowledge to the test! 💪 Instead of learning something new, I took on a full practice session covering everything I've studied so far on Python's core data structures. 🧪 Here's what I worked through: ✅ Lists — creating, slicing, methods like append(), extend(), insert(), pop(), remove(), and sort() ✅ List Comprehensions — squares, filters, tuple pairs, and more ✅ Tuples — declaration, immutability (yes, I triggered the TypeError 😅), unpacking, and zip() ✅ Sets — deduplication, membership checks, add/remove/discard, and set operations like union, intersection, difference & symmetric difference ✅ Dictionaries — key-value access, get(), items(), keys(), values(), nested dicts, and updating/deleting entries ✅ Dictionary Comprehensions — building mappings with filters ✅ Applied Problems — frequency maps, common elements using sets, zip() with conditional logic The practice set had 30+ exercises and solving each one back-to-back really helped solidify the concepts rather than just reading about them. Key takeaway from today: You don't truly understand a concept until you've broken it, debugged it, and fixed it yourself. 🔧 On to Day 6! 🚀 #Python #100DaysOfCode #DataStructures #LearningInPublic #CodingJourney #PythonProgramming
To view or add a comment, sign in
-
🚨 This behavior of Python might look like a BUG… but it isn’t actually. a = 10 b = 10 print(id(a)) print(id(b)) 👉 Same memory location 😲 “Why do we have two variables pointing to the same memory location?!” Here comes the second one and things get interesting 👇 a = [1, 2, 3] b = a b.append(4) print(a) # [1, 2, 3, 4] 🔥 👉 Hmmm… why did ‘a’ change?! 💡 Explanation: ⭐ id() returns the identity of an object ⭐ Python reuses memory locations for immutable values ⭐ For mutable objects however, there is no copying, just pointers! ⚠️ The misconception: Most people believe ‘=’ copies objects in variables. 👉 Nope! ✅ Solution: b = a.copy() Now the two variables are separate ✅ 🔥 Consequence: It can seriously mess up your program’s logic! Ever got caught by such a ghost bug in Python? 👇 #CodeWithSujith #Python #Programming #Coding #PythonTricks #LearnPython #PythonBeginner #100DaysOfCode #DeveloperJourney
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