🧠 Reverse a list | Python Problem Statement Given a list of n elements, reverse the list in place. 📌 Examples Input: n=5 myList = [20,1,10,5,59] Output: [59,5,10,1,20] 🔍 Approach Brute Force Approach 1. Traverse the list and store elements in a temporary list in reverse order 2. Copy the temporary list back to the original list ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) ⚠️ This approach is easy to understand but uses extra space. Optimized Approach (Two-Pointer Technique) 1. Initialize two pointers: left = 0 and right = n − 1 2. Swap elements at left and right 3. Increment left and decrement right 4. Repeat until left < right ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) 🧪 Python Code def reverse(self, arr: list, n: int) -> None: left = 0 right = n-1 while left < right: arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 🧩 Edge Cases (Interview Tip) Empty list → no change Single-element list → already reversed List with duplicate elements → handled naturally #Python #DSA #CodingInterview #InterviewPreparation #CollegeStudents #CampusPlacements #LearningInPublic
Reverse List in Place with Python
More Relevant Posts
-
🧠 Python Concept That Makes Code Cleaner: enumerate() vs range(len()) Most people still write this 👇 names = ["Asha", "Rahul", "Zoya"] for i in range(len(names)): print(i, names[i]) Works… but it’s not Pythonic 😬 ✅ Pythonic Way for i, name in enumerate(names): print(i, name) Same result. Cleaner. Safer. More readable ✨ 🧒 Simple Explanation Imagine calling roll numbers in class 🧑🏫 Python gives you: the number 🧾 and the name 👤 together — no counting needed. 💡 Why This Matters ✔ Avoids index mistakes ✔ Reads like English ✔ Cleaner loops ✔ Very common interview question ⚡ Bonus Tip Start counting from 1 👇 for i, name in enumerate(names, start=1): print(i, name) 💻 Clean code isn’t about fewer lines. 💻 It’s about clear intent 🐍✨ 💻 If you’re still using range(len()), Python has a better idea. #Python #PythonTips #PythonTricks #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 Count the Digits That Divide a Number | Python Problem Statement Given an integer n, return the number of digits in n that evenly divide n. 📌 Examples Input: n=248 Output: 3 Explanation: 248 is divisible by 8, 4, 2, hence the output is 3 🔍 Approach 1. Extract the last digit using % 10 2. If the digit is non-zero and divides the original number, increment the count 3. Remove the last digit using // 10 4. Stop when the number becomes 0 🧪 Python Code def countDigits(num: int) -> int: original = num countNum = 0 while num > 0: digit = num % 10 if digit != 0 and original % digit == 0: countNum += 1 num //= 10 return countNum ⏱️ Complexity Time: O(log₁₀ n) Space: O(1) 🧩 Edge Cases (Interview Tip) 1. Digits equal to 0 → ignored (division by zero) 2. Single-digit numbers → handled naturally 3. Negative numbers → clarify constraint or use abs(n) #Python #DSA #CodingInterview #InterviewPreparation #CollegeStudents #CampusPlacements #LearningInPublic
To view or add a comment, sign in
-
🧠 Python Feature That Feels Like a Cheat Code: enumerate() Most beginners write this 👇 i = 0 for item in items: print(i, item) i += 1 But Python says… why work so hard? 😌 ✅ Pythonic Way for i, item in enumerate(items): print(i, item) 🧒 Simple Explanation Imagine numbering students in a line 🧑🎓 enumerate() gives you: ✨ the number ✨ the student at the same time 🎯 💡 Why It’s Important ✔ Cleaner code ✔ Fewer bugs ✔ More readable ✔ Very common in interviews ⚡ Bonus Tip Start counting from 1: for i, item in enumerate(items, start=1): print(i, item) ✔️ Python rewards clean thinking. ✔️ If you’re manually counting in a loop… Python already has a better way 🐍✨ #Python #PythonTips #CleanCode #LearnPython #DeveloperLife #Coding
To view or add a comment, sign in
-
-
Here’s a small Python program that works like a polite bouncer at a party 😄 — it only lets unique guests in and politely ignores duplicates! 🧠 What this code does: We create a function unique(li) that: Takes a list as input Checks each item one by one Adds it to a new list only if it hasn’t appeared before 📌 Input: lst = [1,2,3,1,2,4] 🎯 Output: [1, 2, 3, 4] Why this is useful for beginners: ✔ Understand lists in Python ✔ Learn how loops work ✔ Practice conditional logic (if i not in ...) ✔ Build problem-solving skills Simple logic, powerful concept, and super useful in real-world coding 🚀 lst = [1,2,3,1,2,4] def unique(li): uniquelist =[] for i in li: if i not in uniquelist: uniquelist.append(i) return uniquelist unq = unique(lst) print(unq) #Python #Coding #Programming #BeginnerToPro #DataScience #LearnWithFun
To view or add a comment, sign in
-
-
🚀 Post #351 — Learning Python the Right Way Most people can write this in Python: a = 10 But when I asked where does a actually live in memory? Silence. That’s the gap between using Python and understanding Python. 🧠 In Python, variables don’t store values. They store references to objects. a = 10 print(id(a)) 🔍 id() gives you the memory address (identity) of the object a points to. Why this matters in real systems 👇 • Explains immutability (int, str, tuple) • Prevents bugs in shared references & mutability • Helps debug weird behavior in lists, dicts, function calls • Builds a strong base for performance + memory reasoning Example that changes how you think: a = 10 b = 10 print(id(a) == id(b)) # True (integer caching) Python is doing memory optimization, not magic. If you skip internals like this, you’ll write code — but you won’t reason about it. Curiosity at the memory level is what separates script writers from engineers. 🐍 #Python #SoftwareEngineering #BackendDevelopment #LearningInPublic #ComputerScience
To view or add a comment, sign in
-
-
A Python f-string (formatted string literal) is a way to embed expressions directly inside string constants, introduced in Python 3.6. It makes it easy to insert variable values into strings without needing concatenation or the .format() method. Syntax: name = "Sam" age = 30 print(f"My name is {name} and I am {age} years old.") Output: My name is Sam and I am 30 years old. How it works: The f before the opening quote tells Python to interpret the string as an f-string. Expressions inside {} are evaluated and replaced with their values. Benefits: Clean and readable More concise than using + or .format() You can use any valid Python expression inside the {} (e.g. {age + 5}, {name.upper()}) #Python #f-strings
To view or add a comment, sign in
-
-
If Python is a "memory managed" language, but who is managing it? Reference Counter! Reference counter is what decides exactly when an object lives and when it dies in python. As discussed in previous posts, every object in Python carries a hidden counter. This counter tracks exactly how many variables are currently pointing to it. How it works? 1. Assignments: When we do y = x, Python finds the object x is pointing to and increments its counter (+1). 2. Deletions: When we do del x, Python finds the object x is pointing to and decrements its counter (-1). 3. Scope Exit: When a function finishes, all variables inside that function disappear. Python automatically decrements the counter of the objects they pointed to (-1). The moment that counter hits 0, Python immediately deletes the object and frees the memory. While this system is fast, it isn't "thread-safe". If two threads try to update the counter at the exact same time, the tally can get corrupted. That is exactly the reason, Python has Global Interpreter Lock(GIL) in place. Will discuss about it in more detail in next post. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
🦭 Understanding the Walrus Operator (:=) in Python 🐍 Introduced in Python 3.8, the walrus operator (:=) allows you to assign and return a value in a single expression. It helps reduce redundancy and improves readability when used thoughtfully. 🔹 What does it solve? Without the walrus operator, values often need to be computed twice or stored separately before a condition. With :=, you can assign inline while evaluating an expression. 🔹 Common Use Cases ✔ Conditional checks if (n := len(data)) > 10: print(f"Large dataset with {n} items") ✔ While loops while (line := file.readline()): process(line) ✔ Avoiding repeated function calls if (result := expensive_call()) is not None: handle(result) ✔ List comprehensions filtered = [y for x in values if (y := transform(x)) > 0] 🔹 Why it matters • Improves performance by avoiding duplicate computations • Makes code more expressive and concise • Keeps related logic closer together ⚠ Use with care Overusing the walrus operator can reduce readability. It’s best applied when it simplifies logic, not when it makes code harder to follow. 💡 A powerful feature when used responsibly — clarity always comes before cleverness. #Python #AdvancedPython #WalrusOperator #ProgrammingTips #CleanCode #Python3 #DeveloperLearning
To view or add a comment, sign in
-
🚀 What I Revised today in Python: 💡 Variable in python: a=12 12 will get stored into RAM and a will hold the address of 12. print(id(12)) hashtag#output: 4404716384 a=12 print(id(a)) hashtag#output: 4404716384 🤔 proof using id()-----> id tells the memory address a=12 b=a print(id(a)) print(id(b)) hashtag#output: 4404716384 4404716384 a and b have the same memory address. a and b refer to same memory address. # this clears that 12 is stored into RAM, a and b stores the address of RAM. 👍 Clean variable names in python? use clear, descriptive and readable variable names------your future self will thank you! ✅ Good practice: clear and readable user_age=23 total_price=43.33 is_logged_in=True ❌ Avoid: unclear x=25 tp=49.99 p=True 💡 Tip: 1. Use snake_case_name. e.g., user_name, item_count 2. Don't reuse variable names for different things.
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