Day 12/365: Checking If a List Is a Palindrome in Python 🔁 Today I solved a classic problem in Python: checking whether a list is a palindrome or not — using the two‑pointer technique with a for-else loop. 🔍 How this works step by step: I start with a list l that has elements arranged symmetrically. To check if it’s a palindrome, I compare elements from both ends: l[0] with l[-1], l[1] with l[-2], and so on. I only need to go till the middle of the list: range(len(l)//2) Inside the loop: If any pair doesn’t match, I print "list is not palindrome" and use break to exit the loop early. The interesting part is the for-else: The else block runs only if the loop finishes without hitting a break. That means all pairs matched, so I print "list is palindrome". 💡 What I learned: How to use the two‑pointer technique to compare elements from start and end efficiently. How Python’s for-else works — the else is tied to the loop, not the if. Why we only need to iterate till the middle of the list for palindrome checking. How the same logic can be reused for: checking if a string is a palindrome, validating symmetric data in lists and arrays. Day 12 done ✅ 353 more to go. If you have ideas like: checking palindromes while ignoring cases/spaces in strings, handling mixed data types in lists, or checking palindromes in other data structures, drop them in the comments — I’d love to try them next. #100DaysOfCode #365DaysOfCode #Python #LogicBuilding #TwoPointers #Lists #CodingJourney #LearnInPublic #AspiringDeveloper
Checking if a List Is a Palindrome in Python
More Relevant Posts
-
Many Python I/O tutorials end at print() and open(). This one goes further. On PythonCodeCrack there's a full beginner tutorial on Python I/O that covers the ground many skip — not just how to use the tools, but why they work the way they do. What's inside: — stdin, stdout, and stderr: what they are, where they come from, and why Python didn't invent them — print() in full: sep, end, flush, and why flush=True doesn't mean your data is on disk — input() and why it always returns a string no matter what the user types — File modes r, w, a, and x — including why 'w' truncates before the first write, not during it — The three-layer CPython I/O stack (TextIOWrapper → BufferedWriter → FileIO) and how to inspect it live — PEP 393: why a single emoji in a 2 GB text file can force 4 bytes per character across the entire string — buffering=1 line-buffered mode for crash-safe log files — flush() vs os.fsync() — two entirely different operations that most tutorials treat as the same thing — Python 3.15 making UTF-8 the default on all platforms, and what that means for existing code — sys.__stdout__ vs sys.stdout, newline translation, file descriptors, and TOCTOU race conditions The tutorial includes interactive quizzes, spot-the-bug challenges, a code builder, predict-the-output exercises, a 15-question final exam, and a downloadable certificate of completion. https://lnkd.in/gbYPmYgv #Python #PythonProgramming #LearnPython #CodingEducation
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
-
Hello there and welcome to this new section called: 'Learning Python with me'. Today, I will bring you one of the most basic commands, and we will create a name generator using Python. I am very excited to start this project and have you coming along with me! Scenario: We have a friend who has a beer company. He has everything: the product, the manufacturing, and the investment. But he is missing one single thing—the name of the company. He is struggling to think about it and asked us for help to create a name for him. We will use Python to generate two questions and combine them to create his beer company name! What will we use in Python: As you can see in the video, I am starting by leaving notes in Python. However, these notes cannot be left by themselves; they need to be preceded by a "#" symbol, which makes Python understand we are leaving comments instead of writing code. Variables: Variables are containers used to store data values. You create one by giving it a name and assigning a value using the "=" operator. Strings: Strings are sequences of text. In Python, they must be wrapped in either single quotes (' ') or double quotes (" "). Input: input() is a way to get information from the user. It allows the program to 'pause' and wait for you to type something into the console. So, as you can see, we are combining strings and inputs in the video. Why am I mentioning variables if I did not use them in the code? Because variables and strings tend to go together, so I could have used a variable to store and print the strings, something like this: result = ("The beer company name is: " + input("What is your favorite color?: ") + input("What is your favorite animal?: ")) print(result) This works exactly like the example in the video (you can test it). It's just that I put the print statement directly on the same line. As programmers, we want to save as much work as possible, so we keep everything clean and easy to read. I hope you enjoy it!" #Python #PythonProject #personalproject #DataScience #SideProject.
To view or add a comment, sign in
-
🚀 Mastering Loops in Python 🐍 Loops in Python are essential for repeating tasks efficiently. They allow you to iterate over a sequence of elements such as lists or strings, executing the same block of code multiple times. This is incredibly useful for automating repetitive operations and processing large amounts of data in your programs. For developers, understanding loops is crucial as they form the backbone of many algorithms and data processing tasks. By mastering loops, you can write more concise and elegant code, improving the efficiency and readability of your applications. 🔎 Let's break it down step by step: 1️⃣ Initialize a counter variable 2️⃣ Set the condition for the loop to continue 3️⃣ Execute the code block inside the loop 4️⃣ Update the counter to progress through the sequence ```python # Example of a for loop in Python for i in range(5): print("Iteration", i) ``` 🚩 Pro Tip: Use `enumerate()` to access both the index and value of an item in a loop effortlessly. ❌ Common Mistake: Forgetting to update the counter variable in a loop, leading to an infinite loop and crashing your program. 🤔 What's your favorite use case for loops in Python? 🌐 View my full portfolio and more dev resources at tharindunipun.lk #PythonProgramming #DeveloperTips #CodingCommunity #LearnToCode #LoopInPython #CodeNewbie #TechTalks #ProgrammingLife
To view or add a comment, sign in
-
-
Built a simple calculator using Python 🧮 Recently completed the basics of: • Variables • User Input • Conditional Statements (if/elif/else) Applied these concepts to create this small project. Looking forward to building more as I continue learning Python 🚀 Here’s the code: ```python a = int(input("what is first value: ")) b = input("what you want to do: ") c = int(input("what is second value: ")) if b == "+": print("your result is", a + c) elif b == "-": print("your result is", a - c) elif b == "*": print("your result is", a * c) elif b == "/": print("your result is", a / c) ``` #Python #CodingJourney #BeginnerProject #LearningByDoing
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
-
-
I’m excited to share pyssa, an experiment in designing an intermediate representation for Python that aims to bridge a common gap in Python tooling. Today, Python workflows often have to choose between: - ASTs, which preserve source structure well but are not directly executable - Bytecode, which is executable but less source-oriented and more tied to interpreter internals pyssa explores a middle ground: a region-based, explicit control-flow IR for Python that stays close to the source program while also being directly executable. The current prototype already supports: - lowering from Python source - execution through an interpreter - validation against CPython for a substantial subset of Python My goal is to explore whether this kind of IR could serve as a more stable foundation for future Python analysis and transformation tools. Resources: - Zenodo: https://lnkd.in/gVTMAp8E - DOI: https://lnkd.in/gAf3_u-g - GitHub: https://lnkd.in/gr92YQbz If you work on Python tooling, compilers, static analysis, or program transformation, I’d love to hear your thoughts. #Python #Compilers #ProgrammingLanguages #StaticAnalysis #SoftwareEngineering #OpenSource
To view or add a comment, sign in
-
NumPy vs Pure Python: A 3.3x SpeedUp I just benchmarked calculating mean, median, and mode on 10,000 numbers: Pure Python: 0.141 seconds NumPy: 0.043 seconds Speedup: 3.3x "But wait... isn't NumPy just Python too?" Actually, I was surprised: shouldn't pure Python be faster since NumPy is built on top of Python? Then I searched for why this actually happened and what's going on under the hood. That means: 1. Implementing from scratch takes more time to write code 2. Implementing from scratch takes more time to execute code Here's what's actually happening under the hood: 1️⃣ VECTORIZATION Pure Python: Loops through each element (interpreter overhead) NumPy: C-compiled operations on entire arrays 2️⃣ MEMORY EFFICIENCY Python lists: Scattered pointers across memory NumPy arrays: Contiguous blocks → cache-friendly 3️⃣ ZERO TYPE OVERHEAD Python: Type-checks every element, every operation NumPy: Homogeneous arrays → check once 4️⃣ CPU-LEVEL OPTIMIZATION NumPy leverages SIMD instructions (process multiple numbers simultaneously) Code: https://lnkd.in/g7wsVFXp #Python #DataScience #Performance #NumPy #Programming #MachineLearning
To view or add a comment, sign in
-
-
Most Python code looks simple until you realize how much is happening under the surface. Take this for example: _C = (1, 2, 3) a, b, c = _C print(a) This is iterable unpacking, more precisely Python’s way of doing positional destructuring assignment. What actually happens: _C is evaluated as an iterable Python matches elements positionally Each value is bound in a single atomic assignment step So internally: a = _C[0] b = _C[1] c = _C[2] This pattern is not just syntactic sugar, it is widely used in production code: Function return unpacking (return x, y) Iteration over structured data API responses and tuple-based records Why it matters: Removes manual indexing (less error prone) Improves intent readability Makes transformations explicit and compact One important constraint: If the structure does not match, Python fails fast with a ValueError, which is often a feature, not a bug. Clean syntax, strict alignment, predictable behavior. That is the philosophy behind Python’s design. Which Python feature felt too simple until you saw it in real systems? #Python #SoftwareEngineering #CleanCode #Programming #PythonTips #Coding #Developer #SystemDesign
To view or add a comment, sign in
-
If your Python scripts are making 50 API calls, synchronous code spends most of its time waiting around doing absolutely nothing. Suresh Vina has written an intro to async Python using a simple analogy: boiling a kettle and making toast at the same time. Sync code does one, then the other. Async runs both concurrently. Same two tasks: 5 seconds sync, 3 seconds async. It’s not a big deal when making breakfast. But scale that concept across dozens of API calls and the difference adds up. The Infrahub Python SDK supports both sync and async natively. Switching between them is simple. Suresh walks through the core concepts, shows side-by-side code examples, and builds up to running the same operation across multiple sites concurrently. If async Python has been sitting on your "I should learn that someday" list, now’s your chance to *get up to speed*. (See what we did there? 😉) Link in comments 👇
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