<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by sujith t s on Medium]]></title>
        <description><![CDATA[Stories by sujith t s on Medium]]></description>
        <link>https://medium.com/@tssujith2002?source=rss-cbee294ca0e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s3vCy25s0Yjz8PMZ9bpOhw.jpeg</url>
            <title>Stories by sujith t s on Medium</title>
            <link>https://medium.com/@tssujith2002?source=rss-cbee294ca0e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:09:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tssujith2002/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Escaping the Loop: How to Conquer Circular Import Errors in Django]]></title>
            <link>https://medium.com/@tssujith2002/escaping-the-loop-how-to-conquer-circular-import-errors-in-django-b47ddf6bfafd?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b47ddf6bfafd</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[circular-import]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 06:49:56 GMT</pubDate>
            <atom:updated>2025-12-15T07:00:28.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="visualization of circular import" src="https://cdn-images-1.medium.com/max/827/1*RNI_Stufvje8sZGkbGmAPQ.jpeg" /></figure><p>Circular import errors are one of the most frustrating issues Python developers face, especially when working with Django. If you’ve ever seen an `ImportError` or `CircularImportError` that seemed impossible to debug, you’re not alone.</p><p><strong>What is a Circular Import Error?</strong>A circular import error occurs when two or more Python files depend on each other to load, creating a loop that Python cannot resolve.<strong>The Core Problem: Import-Time vs Runtime . </strong>To understand circular imports, you need to grasp one crucial concept: <strong>when </strong>Python executes code.</p><p><strong>Import-time </strong>is when Python reads and executes the top-level code in a module (everything not inside a function or class).</p><p><strong>Runtime</strong> is when your functions and methods actually execute, after all modules are loaded.</p><p>Circular imports happen when module A needs something from module B <strong>at import-time</strong>, and module B needs something from module A <strong>also at import-time</strong>.</p><p>Let’s examine a common Django scenario that causes circular imports.</p><p><strong>Example 1: Settings and Utilities</strong></p><p><strong>The Problem Code</strong></p><pre># config/settings.py<br>from send_mail_app.utils import calculate_upload_path<br>DEBUG = True<br>MEDIA_ROOT = calculate_upload_path() # Needs utils AT IMPORT TIME<br>SECRET_KEY = &#39;your-secret-key&#39;<br><br># send_mail_app/utils.py<br>from config.settings import DEBUG # Needs settings AT IMPORT TIME<br>def calculate_upload_path():<br>  if DEBUG:<br>    return &#39;/tmp/uploads/&#39;<br>  return &#39;/var/www/uploads/&#39;</pre><p><strong>Why This Crashes</strong></p><p>1. Python starts loading `settings.py`</p><p>2. It hits `from send_mail_app.utils import calculate_upload_path` and pauses</p><p>3. Python opens `utils.py`</p><p>4. It hits `from config.settings import DEBUG` and tries to access `settings.py`</p><p>5. <strong>CRASH</strong>: `settings.py` is only partially loaded — `DEBUG` doesn’t exist yet!</p><p><strong>The Django Solution: Lazy Settings</strong></p><p>Django provides a special `settings` object that acts as a proxy:</p><pre># send_mail_app/utils.py(Fixed)<br>from django.conf import settings # Import Django&#39;s settings proxy<br>def calculate_upload_path():<br>  # This accesses settings.DEBUG at RUNTIME, not import-time<br>  if settings.DEBUG:<br>    return &#39;/tmp/uploads/&#39;<br>  return &#39;/var/www/uploads/&#39;<br><br># config/settings.py<br><br>from send_mail_app.utils import calculate_upload_path<br>DEBUG = True<br>MEDIA_ROOT = calculate_upload_path() # Now this works!<br>SECRET_KEY = &#39;your-secret-key&#39;</pre><p><strong>Why it works</strong>: `from django.conf import settings` doesn’t actually load your `settings.py` file. It imports a lazy proxy that only looks up values when you access them inside functions (at runtime), after all modules are loaded.</p><p><strong>Example 2: Models and Managers</strong></p><p>This is an extremely common pattern that trips up beginners.</p><p>The Problem code:</p><pre># blog/models.py<br><br>from blog.managers import PublishedPostManager<br>class Post(models.Model):<br>  title = models.CharField(max_length=200)<br>  is_published = models.BooleanField(default=False)<br>  objects = PublishedPostManager() # Custom manager<br><br># blog/managers.py<br><br>from django.db import models<br>from blog.models import Post # CIRCULAR IMPORT!<br>class PublishedPostManager(models.Manager):<br>  def get_queryset(self):<br>    return super().get_queryset().filter(is_published=True)<br>  def get_latest(self):<br>    # We want to reference the Post model here<br>    return Post.objects.order_by(&#39;-created_at&#39;).first()<br><br></pre><p>The Better Solution:</p><pre># blog/managers.py (Fixed)<br>from django.db import models<br>class PublishedPostManager(models.Manager):<br>  def get_queryset(self):<br>    return super().get_queryset().filter(is_published=True)<br>  def get_latest(self):<br>    # Access the model through self.model instead of importing<br>    return self.model.objects.order_by(&#39;-created_at&#39;).first()<br></pre><p>Django’s managers automatically have access to their model through `self.model`, so you don’t need to import it.</p><p><strong>Tips to Avoid Circular Imports</strong></p><p><strong>1. Use Django’s String References</strong></p><p>Django allows you to reference models as strings in many places:</p><pre># In ForeignKey<br>user = models.ForeignKey(&#39;auth.User&#39;, on_delete=models.CASCADE)<br># In signals<br>@receiver(post_save, sender=&#39;products.Product&#39;)<br># In permissions<br>permission_classes = [&#39;myapp.CanEditProduct&#39;]</pre><p><strong>2. Import Inside Functions (Last Resort)</strong></p><p>If you really need to import something that would cause a circular import, do it inside the function:</p><pre>def my_function():<br>  from some_app.models import SomeModel # Import at runtime<br>  return SomeModel.objects.all()</pre><p><strong>Warning</strong>: This is a code smell. If you find yourself doing this often, restructure your code.</p><p><strong>3. Organize Your Django App Structure</strong></p><p>Keep your imports flowing in <strong>one direction </strong>(downwards) to avoid loops.</p><p><strong>The Safe Import Order:</strong></p><p>1. `models.py` (The Foundation — Independent)</p><p>2. `serializers.py` / `forms.py` (Depends on Models)</p><p>3. `views.py` (Depends on Serializers &amp; Models)</p><p>4. `urls.py` (Depends on Views)</p><p><strong>Rule:</strong> A file can only import from files <strong>above</strong> it in this list.</p><ul><li>`views.py` imports `models.py` (Good)</li><li>`models.py` imports `views.py` (Crash!)</li></ul><p><strong>4. Use get_model() for Dynamic Imports</strong></p><p>Django provides a function to get models dynamically:</p><pre>from django.apps import apps<br>def my_utility_function():<br>  Product = apps.get_model(&#39;products&#39;, &#39;Product&#39;)<br>  return Product.objects.filter(is_active=True)</pre><p>By understanding the difference between import-time and runtime execution, you’ll write cleaner Django code and avoid the circular import trap.</p><p>Remember: when in doubt, move the import inside the function or use Django’s built-in lazy loading mechanisms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b47ddf6bfafd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Squashing: Because Your Team Doesn't Need to See All Your 'oops' Moments]]></title>
            <link>https://medium.com/@tssujith2002/git-squashing-because-your-team-doesnt-need-to-see-all-your-oops-moments-8a6fe0194070?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a6fe0194070</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-squash]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 09:24:39 GMT</pubDate>
            <atom:updated>2025-10-04T09:24:39.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eb52dCEnr5-n_yGUaMNoIA.png" /></figure><p><strong>Ever looked at your Git commit history and felt like you were sifting through a messy attic?</strong> “WIP,” “fix bug,” “oops,” “another try” — these temporary messages accumulate, making it difficult to understand the journey of your code. This is where Git squashing comes in, transforming your chaotic commit log into a clear, professional narrative.</p><blockquote><strong>What is Git Squashing? The Art of Condensing History</strong></blockquote><p>Imagine you’re writing a book. During the drafting phase, you might have many scribbled notes, minor edits, and rephrased sentences. But when it’s time to publish, you present a polished, cohesive chapter — not the raw stream of consciousness. Git squashing does exactly this for your codebase.</p><p><strong>Git squashing is the process of combining multiple individual commits into a single, more meaningful commit.</strong> It’s like taking all those small, iterative steps you made during development and rolling them up into one significant milestone.</p><p><strong>Key Differences at a Glance:</strong></p><ul><li><strong>Regular Merge:</strong> Preserves every individual commit from the merged branch. Think of it as copying all your draft notes into the final book.</li><li><strong>Squash Merge:</strong> Combines all commits from the source branch into one new commit on the target branch. This is like summarizing all your draft notes into a single, well-articulated point.</li><li><strong>Rebase:</strong> Rewrites commit history by moving or combining commits. Squashing is a powerful feature <em>within</em> rebase, offering granular control.</li></ul><blockquote><strong><em>Three Ways to Squash</em></strong></blockquote><p><em>1. Interactive Rebase</em></p><p><em>2. Soft Reset</em></p><p><em>3. GitLab/GitHub UI Squash</em></p><blockquote><strong><em>1. Interactive Rebase</em></strong></blockquote><p>Interactive rebase (git rebase -i) is your most powerful tool for shaping history. It gives you full control over which commits to squash, reorder, or edit. <strong>Scenario:</strong> You’ve been working on a new feature (feat-xyz) and have three commits: “xyz 1,” “xyz 2,” and “xyz 3.” You want to combine these into one clean commit before pushing.</p><p>i) <strong>Start the Interactive Rebase:</strong><br>First, let’s see your commit history (e.g., git log — oneline). Assume you want to squash the last 3 commits.</p><pre>git rebase -i HEAD~3</pre><p>This command opens an editor (often Vim or your default editor) showing your commits. It will look something like this, along with helpful instructions:</p><pre>pick b61a85b xyz 1 .. before rebase<br>pick 0803cf3 xyz 2 .. before rebase<br>pick 8b08ea6 xyz 3 .. before rebase<br><br># Rebase 0f760f5..8b08ea6 onto 0f760f5 (3 commands)<br>#<br># Commands:<br># p, pick &lt;commit&gt; = use commit<br># r, reword &lt;commit&gt; = use commit, but edit the commit message<br># e, edit &lt;commit&gt; = use commit, but stop for amending<br># s, squash &lt;commit&gt; = use commit, but meld into previous commit<br># f, fixup [-C | -c] &lt;commit&gt; = like &quot;squash&quot; but keep only the previous<br>#                    commit&#39;s log message, unless -C is used, in which case<br>#                    keep only this commit&#39;s message; -c is same as -C but<br>#                    opens the editor<br># x, exec &lt;command&gt; = run command (the rest of the line) using shell<br># b, break = stop here (continue rebase later with &#39;git rebase --continue&#39;)<br># d, drop &lt;commit&gt; = remove commit<br># l, label &lt;label&gt; = label current HEAD with a name<br># t, reset &lt;label&gt; = reset HEAD to a label<br># m, merge [-C &lt;commit&gt; | -c &lt;commit&gt;] &lt;label&gt; [# &lt;oneline&gt;]<br>#         create a merge commit using the original merge commit&#39;s<br>#         message (or the oneline, if no original merge commit was<br>#         specified); use -c &lt;commit&gt; to reword the commit message<br># u, update-ref &lt;ref&gt; = track a placeholder for the &lt;ref&gt; to be updated<br>#                       to this position in the new commits. The &lt;ref&gt; is<br>#                       updated at the end of the rebase<br>#</pre><p>ii) <strong>Mark Commits for Squashing:</strong><br>Change pick to squash (or s) for the commits you want to merge <em>into the one directly above it</em>. The <em>first</em> pick in the sequence will be the base for the new squashed commit message.</p><pre>pick b61a85b xyz 1 .. before rebase<br>squash 0803cf3 xyz 2 .. before rebase<br>squash 8b08ea6 xyz 3 .. before rebase</pre><p>iii)<strong>Edit the New Commit Message:</strong><br>Save and exit the first editor. A new editor will open, allowing you to craft a single, descriptive commit message for the combined changes. Git pre-populates it with the original messages:</p><pre># This is a combination of 3 commits.<br># This is the 1st commit message:<br><br>xyz 1 .. before rebase<br><br># This is the commit message #2:<br><br>xyz 2 .. before rebase<br><br># This is the commit message #3:<br><br>xyz 3 .. before rebase<br><br># Please enter the commit message for your changes. Lines starting<br># with &#39;#&#39; will be ignored, and an empty message aborts the commit.<br>#<br># Date:      Sat Oct 4 13:51:53 2025 +0530<br>#<br># interactive rebase in progress; onto 0f760f5<br># Last commands done (3 commands done):<br>#    squash 0803cf3 xyz 2 .. before rebase<br>#    squash 8b08ea6 xyz 3 .. before rebase<br># No commands remaining.<br># You are currently rebasing branch &#39;feature/feat-xyz&#39; on &#39;0f760f5&#39;.<br>#<br># Changes to be committed:<br>#       new file:   branch_check/feat_xyz1.txt<br>#       new file:   branch_check/feat_xyz2.txt<br>#       new file:   branch_check/feat_xyz3.txt</pre><p>Replace this with your desired, concise message, for example:</p><pre>feat: Combined XYZ 1, 2, and 3 into one comprehensive feature update<br><br>This commit introduces the complete set of changes for the XYZ feature,<br>including initial setup, minor adjustments, and final refinements.</pre><p>Save and exit this editor. Git will then process the rebase and inform you of the outcome:</p><pre>[detached HEAD 178f268] xyz 1 , 2 and 3 combined thorugh interactive rebase<br> Date: Sat Oct 4 13:51:53 2025 +0530<br> 3 files changed, 3 insertions(+)<br> create mode 100644 branch_check/feat_xyz1.txt<br> create mode 100644 branch_check/feat_xyz2.txt<br> create mode 100644 branch_check/feat_xyz3.txt<br>Successfully rebased and updated refs/heads/feature/feat-xyz.</pre><p>Your commit history on feature/feat-xyz now has one clean commit instead of three!</p><p><strong>iv) Pushing the Rewritten History:</strong><br>If you’ve already pushed your original commits to a remote, your local branch has diverged. You’ll see a status like:</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git status<br>On branch feature/feat-xyz<br>Your branch and &#39;origin/feature/feat-xyz&#39; have diverged,<br>and have 1 and 3 different commits each, respectively.<br>  (use &quot;git pull&quot; if you want to integrate the remote branch with yours)<br><br>nothing to commit, working tree clean</pre><p>To update the remote branch with your new, cleaner history, you must use git push — force-with-lease:</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git push --force-with-lease<br>Enumerating objects: 8, done.<br>Counting objects: 100% (8/8), done.<br>Delta compression using up to 8 threads<br>Compressing objects: 100% (3/3), done.<br>Writing objects: 100% (6/6), 485 bytes | 485.00 KiB/s, done.<br>Total 6 (delta 2), reused 0 (delta 0), pack-reused 0<br>remote:<br>remote: To create a merge request for feature/feat-xyz, visit:<br>remote:   https://gitlab.com/gradspace338/angularjs_demo1/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature%2Ffeat-xyz<br>remote:<br>To https://gitlab.com/gradspace338/angularjs_demo1.git<br> + 8b08ea6...178f268 feature/feat-xyz -&gt; feature/feat-xyz (forced update)<br>sujith@lenovo:~/Desktop/angular_demo$</pre><p>The remote branch is now updated with your single, squashed commit.</p><blockquote><strong>2. Soft Reset: The Quick &amp; Easy Rollback</strong></blockquote><p>The soft reset method is perfect when you want to combine a sequence of your <em>most recent</em> commits into one, without losing any of your actual file changes. It’s like hitting “undo” on your last few commit actions, but keeping all the work you did.</p><p><strong>Scenario:</strong> You’ve been working on a feature/feat-ijk branch and made two small commits: “feat_ijk5.txt” and “feat_ijk6.txt.” Now, you want to combine them into a single, meaningful commit.</p><p>i)<strong>Check Current Status (Optional but good practice):</strong><br>First, ensure your working directory is clean before you start modifying history.</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git status<br>On branch feature/feat-ijk<br>Your branch is up to date with &#39;origin/feature/feat-ijk&#39;.<br><br>nothing to commit, working tree clean</pre><p>ii)<strong>Perform a Soft Reset:</strong><br>You want to combine the last 2 commits. HEAD~2 refers to two commits before your current HEAD.</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git reset --soft HEAD~2</pre><p>After this command, Git “forgets” the last two commits from your local history, but all the changes introduced by those commits are preserved in your working directory and are staged, ready for a new commit. Yourgit status` will now reflect this:</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git status<br>On branch feature/feat-ijk<br>Your branch is behind &#39;origin/feature/feat-ijk&#39; by 2 commits, and can be fast-forwarded.<br>  (use &quot;git pull&quot; to update your local branch)<br><br>Changes to be committed:<br>  (use &quot;git restore --staged &lt;file&gt;...&quot; to unstage)<br>        new file:   branch_check/feat_ijk5.txt<br>        new file:   branch_check/feat_ijk6.txt</pre><p>Notice that the files feat_ijk5.txt and feat_ijk6.txt are still staged, even though their original commits are gone from your local history.</p><p>iii)<strong>Create a New, Consolidated Commit:</strong><br>Now, create a single, descriptive commit that encapsulates all the changes you just “unstaged” from the previous two commits.</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git commit -m &quot;feat: combine ijk 5 and 6 commit using reset --soft head~2&quot;<br>[feature/feat-ijk a673fb0] feat: combine ijk 5 and 6 commit using reset --soft head~2<br> 2 files changed, 2 insertions(+)<br> create mode 100644 branch_check/feat_ijk5.txt<br> create mode 100644 branch_check/feat_ijk6.txt</pre><p><strong>iv)Pushing the Rewritten History:</strong><br>Since you’ve altered your local history (removed the two original commits and added one new one), Git will prevent a regular git push.</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git push<br>To https://gitlab.com/gradspace338/angularjs_demo1.git<br> ! [rejected]        feature/feat-ijk -&gt; feature/feat-ijk (non-fast-forward)<br>error: failed to push some refs to &#39;https://gitlab.com/gradspace338/angularjs_demo1.git&#39;<br>hint: Updates were rejected because the tip of your current branch is behind<br>hint: its remote counterpart. If you want to integrate the remote changes,<br>hint: use &#39;git pull&#39; before pushing again.<br>hint: See the &#39;Note about fast-forwards&#39; in &#39;git push --help&#39; for details.</pre><p>you must use git push — force-with-lease to update the remote branch:</p><pre>sujith@lenovo:~/Desktop/angular_demo$ git push --force-with-lease<br>Enumerating objects: 7, done.<br>Counting objects: 100% (7/7), done.<br>Delta compression using up to 8 threads<br>Compressing objects: 100% (3/3), done.<br>Writing objects: 100% (5/5), 431 bytes | 431.00 KiB/s, done.<br>Total 5 (delta 2), reused 0 (delta 0), pack-reused 0<br>remote:<br>remote: To create a merge request for feature/feat-ijk, visit:<br>remote:   https://gitlab.com/gradspace338/angularjs_demo1/-/merge_requests/new?merge_request%5Bsource_branch%5D=feature%2Ffeat-ijk<br>remote:<br>To https://gitlab.com/gradspace338/angularjs_demo1.git<br> + 6beeae0...a673fb0 feature/feat-ijk -&gt; feature/feat-ijk (forced update)</pre><blockquote><strong>3. GitLab/GitHub UI Squash: The “Set it and Forget it” Approach</strong></blockquote><p>Many modern Git platforms like GitLab, GitHub, and Bitbucket offer a “squash commits” option directly in their Pull Request (or Merge Request) interface. This is often the easiest way to ensure a clean history on your main branch, especially in team environments.</p><p><strong>Scenario:</strong> You’ve finished your feature/dashboard-analytics branch with numerous commits and are ready to merge it into main.</p><ol><li><strong>Create a Pull/Merge Request:</strong> Open a PR from your feature branch to your target branch (main).</li><li><strong>Enable Squashing:</strong> Look for a checkbox or option like “Squash commits” or “Squash and merge” within the merge request settings.</li><li><strong>Complete the Merge:</strong> When you click “Merge,” the platform automatically combines all commits from your feature branch into a single commit on the main branch, using the PR title (or a custom message you provide) as the new commit message.</li></ol><p>This method is ideal for teams where the main branch history needs to be pristine, and the detailed commit history of the feature branch is less critical after merging.</p><h3>Rewriting History: The Golden Rule of git push — force-with-lease</h3><p>When you squash commits using interactive rebase or soft reset, you are rewriting history. This means the commit IDs change. If you’ve already pushed your un-squashed commits to a remote repository, you cannot simply git push again. Git will reject it because your local history diverges from the remote.</p><p>This is where git push — force-with-lease comes in:</p><pre>git push - force-with-lease</pre><p><strong>Why — force-with-lease and not — force?</strong></p><ul><li>— force: Brutally overwrites the remote branch with your local branch, regardless of any new commits that might have been pushed by someone else in the interim. This can lead to data loss for your teammates.</li><li>— force-with-lease: This is the <strong>safer</strong> option. It only forces the push if the remote branch hasn’t been updated by someone else since you last pulled. If someone <em>has</em> pushed new commits, — force-with-lease will fail, preventing you from accidentally overwriting their work.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bfaaU9Pvahun77tnNZWmQ.png" /></figure><p><strong>disclaimer</strong>: Avoid rewriting history on shared branches that others are actively working on. If you must, <strong>always communicate with your team first</strong> to prevent major headaches and lost work. For personal feature branches, squashing before merging to main is generally safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a6fe0194070" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Actions: Your Code’s Personal Assistant]]></title>
            <link>https://medium.com/@tssujith2002/github-actions-your-codes-personal-assistant-a71ecb6d13a3?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a71ecb6d13a3</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 10:17:18 GMT</pubDate>
            <atom:updated>2025-06-29T10:17:18.912Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Imagine having a tireless assistant who works 24/7, automatically testing your code, deploying your apps, and handling routine tasks while you sleep. That’s exactly what GitHub Actions does for developers.</em></p><h3>What is GitHub Actions?</h3><p><strong>GitHub Actions</strong> is like having <strong>smart home automation</strong> for your code. Just as you might program your lights to turn on when you arrive home, you can program GitHub Actions to run tests when you push code, or deploy your app when you merge a pull request.</p><p><strong>Real-world analogy:</strong> It’s your code’s <strong>personal assistant</strong> that automatically handles repetitive tasks.</p><h3>The Building Blocks</h3><p>GitHub Actions works with four main concepts:</p><p>1. Workflows — Your Automation Recipes</p><p>Workflows are like <strong>instruction manuals</strong> stored in workflows folder as YAML files.</p><p>2. Triggers — The Doorbells</p><p>Triggers tell GitHub Actions <strong>when</strong> to run:</p><ul><li><strong>push</strong>: &quot;Run when someone uploads code&quot;</li><li><strong>pull_request</strong>: &quot;Run when someone suggests changes&quot;</li><li><strong>schedule</strong>: &quot;Run at specific times&quot;</li></ul><p>3. Jobs — Your Work Crews</p><p>Jobs are different <strong>teams</strong> handling specific tasks. They can run in parallel or one after another.</p><p>4. Steps — Individual Tasks</p><p>Steps are the <strong>actual commands</strong> that run within each job.</p><h3>Your First Workflow: Hello World</h3><p>Let’s start with a simple example that demonstrates the core concepts:</p><pre>name: Hello World Workflow<br><br>on:<br>  push:<br>    branches: [ main ]<br>  pull_request:<br>    branches: [ main ]<br><br>jobs:<br>  greet:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br>      <br>      - name: Say hello<br>        run: echo &quot;Hello, World! This is my first GitHub Action!&quot;<br>      <br>      - name: Show system info<br>        run: |<br>          echo &quot;Running on: $(uname -a)&quot;<br>          echo &quot;Date: $(date)&quot;<br><br>  farewell:<br>    needs: greet<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Say goodbye<br>        run: echo &quot;Goodbye! The workflow is complete!&quot;</pre><p>This workflow:</p><ol><li><strong>Triggers</strong> when code is pushed to main branch</li><li><strong>First job</strong> checks out code and says hello</li><li><strong>Second job</strong> waits for the first to complete, then says goodbye</li></ol><h3>Real-World Applications</h3><p><strong>Continuous Integration (CI):</strong></p><ul><li>Automatically run tests when code is pushed</li><li>Check code quality and formatting</li><li>Build applications</li></ul><p><strong>Continuous Deployment (CD):</strong></p><ul><li>Deploy to staging when merging to develop branch</li><li>Deploy to production when merging to main branch</li><li>Send notifications when deployments complete</li></ul><p><strong>Automation:</strong></p><ul><li>Generate reports on schedule</li><li>Update dependencies automatically</li><li>Send reminders and notifications</li></ul><h3>Key Concepts You’ll Use</h3><h3>Prebuilt Actions</h3><p>Instead of writing everything from scratch, use <strong>prebuilt actions</strong>:</p><ul><li>actions/checkout@v4: Gets your code</li><li>actions/setup-node@v4: Sets up development environment</li><li>actions/cache@v4: Speeds up workflows by caching dependencies</li></ul><h3>Environment Variables</h3><p>Store configuration values that can be reused:</p><pre>env:<br>  APP_NAME: &quot;My App&quot;<br>  <br>jobs:<br>  build:<br>    steps:<br>      - run: echo &quot;Building $APP_NAME&quot;</pre><h3>Scheduling</h3><p>Run workflows at specific times:</p><pre>on:<br>  schedule:<br>    - cron: &#39;0 2 * * *&#39;    # Every day at 2 AM UTC</pre><h3>Getting Started: Your Action Plan</h3><ol><li><strong>Start Simple</strong>: Create a “Hello World” workflow</li><li><strong>Add Testing</strong>: Set up automatic testing on pull requests</li><li><strong>Add Deployment</strong>: Deploy to staging/production automatically</li><li><strong>Optimize</strong>: Use caching and environment variables</li></ol><h3>Common Pitfalls to Avoid</h3><ul><li><strong>YAML Syntax</strong>: Use spaces, not tabs for indentation</li><li><strong>Branch Names</strong>: Check if your default branch is main or master</li><li><strong>Always Checkout</strong>: Include actions/checkout@v4 to get your code</li><li><strong>Test Manually</strong>: Add workflow_dispatch trigger for manual testing</li></ul><h3>The Bottom Line</h3><p>GitHub Actions transforms your repository from simple code storage into an <strong>intelligent automation hub</strong>. Start simple and gradually add complexity as you learn.</p><p>The best part? You save time, catch bugs automatically, and your deployments become reliable and consistent.</p><h3>Resources and Further Reading</h3><p>For detailed guides and examples, check out the comprehensive documentation:</p><ul><li><strong>Notion Guide</strong>: <a href="https://frosted-jersey-f04.notion.site/GitHub-Actions-Handbook-21cb234dbbae8026b709ffd395c9c1b7">GitHub Actions Handbook</a></li><li><strong>GitHub Repository</strong>: <a href="https://github.com/07SUJITH/gh-actions-basics">gh-actions-basics</a></li></ul><p><em>Ready to automate your development workflow? Start with the hello-world example and watch your productivity soar!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a71ecb6d13a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚙️ Python Generators for Efficient Palindrome Generation]]></title>
            <link>https://medium.com/@tssujith2002/%EF%B8%8F-python-generators-for-efficient-palindrome-generation-7eff4c25e4e9?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eff4c25e4e9</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 10:11:03 GMT</pubDate>
            <atom:updated>2025-06-23T10:11:03.098Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Tired of checking every number to find palindromes?</em></strong><em><br> Discover how </em><strong><em>Python generators</em></strong><em> can efficiently construct palindromes without redundant computation.</em></blockquote><h3>The Problem with Naive Palindrome Search</h3><p>Let’s start with a simple — but flawed — approach:</p><pre>def is_palindrome(n):<br>    return str(n) == str(n)[::-1]<br>n = 0<br>found = 0<br>while found &lt; 20:<br>    if is_palindrome(n):<br>        print(n, end=&quot; &quot;)<br>        found += 1<br>    n += 1</pre><h3>Drawbacks:</h3><ul><li><strong>Inefficient Search</strong>: Checks every number starting from 0.</li><li><strong>Time Complexity</strong>: O(x) where x is much greater than n (the number of palindromes you want).</li><li><strong>Wasteful</strong>: Skips over a huge range of non-palindromes to find each valid result.</li></ul><p>So how do we fix it?</p><h3>The Generator-Based Optimization</h3><p>Instead of testing every number, <strong>what if we just <em>built</em> the palindromes directly?</strong></p><h3>Core Idea:</h3><p>Construct palindromes from their <strong>left-half digits</strong>, then mirror them to form the full number.</p><p>Let &quot;s&quot; be the string of digits:</p><ul><li><strong>Odd-Length Palindromes</strong> → s + s[-2::-1]</li><li><strong>Even-Length Palindromes</strong> → s + s[::-1]</li></ul><p>This guarantees:</p><ul><li>No redundant checks</li><li>Always increasing order</li><li>Constant-time palindrome creation</li></ul><h3>Full Palindrome Generator (Odd + Even Interleaved)</h3><pre>def digit_length_palindrome_generator():<br>    i = 1<br>    while True:<br>        s = str(i)<br>        yield int(s + s[-2::-1])  # Odd-length<br>        yield int(s + s[::-1])    # Even-length<br>        i += 1</pre><pre>print(&quot;Palindrome Generator Using Digit Length&quot;)<br>count = 0<br>for n in digit_length_palindrome_generator():<br>    print(n, end=&quot; &quot;)<br>    count += 1<br>    if count == 22: break</pre><pre>1 11 2 22 3 33 4 44 5 55 6 66 7 77 8 88 9 99 101 1001 111 1111 121</pre><h3>Odd-Length Palindromes Only</h3><pre>def odd_length_palindrome_generator():<br>    i = 1<br>    while True:<br>        s = str(i)<br>        yield int(s + s[-2::-1])<br>        i += 1</pre><pre>print(&quot;First 21 Odd-Length Palindromes&quot;)<br>for i, n in enumerate(odd_length_palindrome_generator()):<br>    print(n, end=&quot; &quot;)<br>    if i == 21: break</pre><pre>1 2 3 4 5 6 7 8 9 101 111 121 131 141 151 161 171 181 191 202 212</pre><h3>Even-Length Palindromes Only</h3><pre>def even_length_palindrome_generator():<br>    i = 1<br>    while True:<br>        s = str(i)<br>        yield int(s + s[::-1])<br>        i += 1</pre><pre>print(&quot;First 21 Even-Length Palindromes&quot;)<br>for i, n in enumerate(even_length_palindrome_generator()):<br>    print(n, end=&quot; &quot;)<br>    if i == 21: break</pre><pre>11 22 33 44 55 66 77 88 99 1001 1111 1221 1331 1441 1551 1661 1771 1881 1991 2002 2112</pre><h3>Generator by Digit Length (Structured Growth)</h3><p>If you want to <strong>control palindromes by length</strong>, here’s a more granular generator:</p><pre>def generate_base10_palindromes():<br>    length = 1<br>    while True:<br>        start = 10 ** ((length - 1) // 2)<br>        end = 10 ** ((length + 1) // 2)<br>        for half in range(start, end):<br>            s = str(half)<br>            if length % 2 == 0:<br>                yield int(s + s[::-1])       # Even-length<br>            else:<br>                yield int(s + s[-2::-1])     # Odd-length<br>        length += 1</pre><pre>for i, n in enumerate(generate_base10_palindromes()):<br>    print(n, end=&quot; &quot;)<br>    if i == 19: break</pre><pre>1 2 3 4 5 6 7 8 9 11 22 33 44 55 66 77 88 99 101 111</pre><h3>Why This Matters</h3><p>Method Complexity Advantage Naive O(x) Easy to understand Generator O(n) Scalable, Fast, Memory-Efficient</p><p>With Python generators:</p><ul><li>No need to store all values in memory.</li><li>You can produce <strong>as many</strong> palindromes as you like, on demand.</li><li>The logic is clear, extendable (e.g., to any base), and performance-friendly.</li></ul><h3>What’s Next?</h3><ul><li>Extend this approach to palindromes in <strong>other bases</strong>.</li><li>Generate <strong>palindromes with constraints</strong> (e.g., digit sum, divisible by 7).</li></ul><h3>Conclusion</h3><p>Python generators are a <strong>powerful abstraction</strong> that let you express complex logic elegantly — especially in problems like palindrome generation, where traditional search becomes inefficient.</p><h3>Follow for more:</h3><p>If you found this helpful, consider following me for more insights on Python patterns, performance tricks, and algorithmic design.</p><blockquote><em>Let your code be lazy — and efficient.<br> </em>Generators will take care of the rest.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eff4c25e4e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python’s List Assignment: A Visual Guide to Shared vs. Separate References]]></title>
            <link>https://medium.com/@tssujith2002/understanding-pythons-list-assignment-a-visual-guide-to-shared-vs-separate-references-c159da88eb09?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c159da88eb09</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 08:48:02 GMT</pubDate>
            <atom:updated>2025-06-02T08:48:02.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L38qiGnruya22igUdmEYMg.png" /><figcaption>shared reference problem .</figcaption></figure><p>Python’s list assignment can be tricky, especially for beginners. When you assign one list to another, you might expect a new, independent copy — but that’s not always the case. This article explores how Python handles list assignments, the pitfalls of shared references, and how to create separate copies</p><h3>The Problem: Shared References</h3><p>In Python, assignment never creates a new object for mutable types like lists. Instead, both variables point to the same underlying data in memory.</p><p>Example:</p><pre>original = [1, 2, 3]  <br>shared = original  # Shared reference!  <br>shared[0] = 99     # Modifies the shared list  <br><br>print(original)  # Output: [99, 2, 3]  <br>print(shared)    # Output: [99, 2, 3]  </pre><h3>The Solution: Creating Independent Copies</h3><p>To avoid shared references, explicitly create a new copy using these methods:</p><h4>1. Shallow Copy with .copy() or list()</h4><p>Creates a new top-level list but shares references to nested objects.</p><pre>original = [1, 2, 3]  <br>separate = original.copy()  # or list(original)  <br>separate[0] = 99  <br>print(original)  # [1, 2, 3] (unchanged)  <br>print(separate)  # [99, 2, 3]</pre><pre># Nested List Shallow Copy Problem<br>original = [[1, 2], [3, 4]]<br><br># Shallow copy (top-level list is copied, inner lists are **referenced**)<br>separate = original.copy()<br><br># Modify top-level reference<br>separate[0] = [&#39;a&#39;, &#39;b&#39;]<br><br>print(&quot;After changing separate[0]:&quot;)<br>print(&quot;original:&quot;, original)    # [[1, 2], [3, 4]] — unchanged, because we reassigned separate[0]<br>print(&quot;separate:&quot;, separate)    # [[&#39;a&#39;, &#39;b&#39;], [3, 4]]<br><br># Now modify a nested element **inside** shared reference<br>original[1][0] = 99<br><br>print(&quot;\nAfter changing original[1][0]:&quot;)<br>print(&quot;original:&quot;, original)    # [[1, 2], [99, 4]]<br>print(&quot;separate:&quot;, separate)    # [[&#39;a&#39;, &#39;b&#39;], [99, 4]] — notice separate ALSO sees the change!</pre><h4>2. Deep Copy with copy.deepcopy()</h4><p>Creates a fully independent copy, including all nested objects.</p><pre>import copy  <br>original = [[1, 2], 3]  <br>deep = copy.deepcopy(original)  <br>deep[0][0] = 99  # Only modifies the deep copy  <br>print(original)  # [[1, 2], 3]  <br>print(deep)      # [[99, 2], 3]</pre><h3>Practical Use Cases</h3><ol><li>Data Processing :Use shallow copies for flat datasets to avoid altering source data.</li><li>Nested Structures (e.g., matrices, JSON):Always use deepcopy to ensure full independence.</li></ol><p>2.Function Arguments: Pass copies to prevent side effects:</p><pre>def process_data(data):  <br>    data_copy = data.copy()  # Avoid mutating input  <br>    # ...  </pre><h3>Debugging Reference Errors</h3><p>Symptom: Changes to one list affect another unexpectedly.<br>Diagnose with id():</p><pre>a = [1, 2, 3]  <br>b = a  <br>c = a.copy()  <br><br>print(id(a) == id(b))  # True (shared reference)  <br>print(id(a) == id(c))  # False (separate copy)  </pre><h3>Common Mistakes &amp; Gotchas</h3><ul><li>Mistake 1: Assuming b = a creates a copy.<br><em>Fix</em>: Use b = a.copy() for shallow copies.</li><li>Mistake 2: Using shallow copies for nested lists.<br><em>Fix</em>: Use copy.deepcopy() for complex structures.</li><li>Gotcha: Slicing (e.g., b = a[:]) is identical to .copy()—shallow only!</li></ul><h3>Key Takeaways</h3><ol><li>Assignment (=) creates shared references—not copies.</li><li>Shallow copies (.copy(), list(), slicing) are sufficient for flat lists.</li><li>Deep copies (copy.deepcopy()) are essential for nested structures.</li><li>Verify independence with id() when debugging.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cea3nE9B5HuKjx2VlgxJmg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c159da88eb09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python’s typing Module and Its Importance in Production Code]]></title>
            <link>https://medium.com/@tssujith2002/understanding-pythons-typing-module-and-its-importance-in-production-code-4113aada38a5?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4113aada38a5</guid>
            <category><![CDATA[ｐｙｔｈｏｎ]]></category>
            <category><![CDATA[data-type]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Fri, 30 May 2025 18:41:49 GMT</pubDate>
            <atom:updated>2025-05-30T18:41:49.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*av_LpPgkMJjBESFM0P6c5Q.png" /></figure><h3>Enhancing Production Code with Type Hints</h3><p>Python is a dynamically typed language, which means you don’t have to declare variable types explicitly. This flexibility makes Python easy to write and read, but it can also lead to bugs that are only caught at runtime. To address this, Python introduced type hints in Python 3.5 through the typing module. Over time, type hints have become a vital tool for writing robust, maintainable production code. This article explores the typing module, its common types with production-ready examples, and why it’s essential for professional development.</p><h3>What Is the typing Module?</h3><p>The typing module provides a standard way to specify the expected data types of variables, function parameters, and return values. This is known as type annotation or type hinting. Type hints don’t affect runtime behavior but enable static analysis tools, IDEs, and team collaboration by making code intent clear.</p><p>For example, instead of writing a function like this:</p><pre>def greet(names):<br>    for name in names:<br>        print(f&quot;Hello, {name}!&quot;)</pre><p>You can use type hints to specify that names should be a list of strings:</p><pre>from typing import List<br><br>def greet(names: List[str]) -&gt; None:<br>    for name in names:<br>        print(f&quot;Hello, {name}!&quot;)</pre><p>This tells developers and tools that names must be a list where each element is a string, and the function returns nothing (None).</p><h3>Common Types in the typing Module</h3><p>The typing module offers a variety of types to describe data structures precisely. Below, we define each common type and provide production-ready function examples relevant to a company setting, such as managing inventory, customers, or analytics.</p><h3>1. List[T]: A list containing items of type T</h3><p>Represents a list where all elements share the same type T.</p><h3>2. Dict[K, V]: A dictionary with keys of type K and values of type V</h3><p>Describes a dictionary with specific key and value types.</p><h3>3. Set[T]: A set of elements of type T</h3><p>Represents a set containing unique elements of type T.</p><h3>4. Union[T1, T2]: An object that can be either type T1 or T2</h3><p>Allows a value to be one of multiple specified types.</p><pre>from typing import List, Dict, Union, Set<br><br>def identify_unique_customers(existing_customers: Set[str], order_records: List[Dict[str, Union[str, int, float]]]) -&gt; Set[str]:<br>    &quot;&quot;&quot;<br>    Used in CRM systems to track customer engagement and activity.<br>    Args:<br>        existing_customers: Set of existing customer IDs (strings) from the database.<br>        order_records: List of dictionaries, each representing an order with fields like<br>                       &#39;order_id&#39; (str), &#39;customer_id&#39; (str), and &#39;amount&#39; (int or float).<br>    Returns:<br>        Updated set of unique customer IDs including those from new orders.<br>    &quot;&quot;&quot;<br>    if not order_records:<br>        return existing_customers<br>    new_customer_ids = set()<br>    for order in order_records:<br>        customer_id = order.get(&#39;customer_id&#39;)<br>        if not isinstance(customer_id, str):<br>            raise TypeError(f&quot;Invalid customer_id type in order {order.get(&#39;order_id&#39;, &#39;unknown&#39;)}: expected str, got {type(customer_id)}&quot;)<br>        new_customer_ids.add(customer_id)<br>    return existing_customers.union(new_customer_ids)</pre><h3>5. Tuple[T1, T2, …]: A tuple with elements of specified types</h3><p>Defines a tuple with a fixed number of elements, each with a specific type.</p><pre>from typing import List, Dict, Union, Tuple<br><br>def get_sales_summary(sales_records: List[Dict[str, Union[int, float, str]]]) -&gt; Tuple[float, float, int]:<br>    &quot;&quot;&quot;<br>    Used in financial reporting for management dashboards and analytics.<br>    <br>    Args:<br>        sales_records: List of dictionaries, each representing a sale with fields like<br>                       &#39;sale_id&#39; (str), &#39;amount&#39; (float or int), and &#39;date&#39; (str).<br>    Returns:<br>        Tuple of (total sales amount, average sale amount, number of transactions).<br>    &quot;&quot;&quot;<br>    if not sales_records:<br>        return (0.0, 0.0, 0)<br>    total = 0.0<br>    count = 0<br>    for record in sales_records:<br>        amount = record.get(&#39;amount&#39;, 0)<br>        if not isinstance(amount, (int, float)):<br>            raise TypeError(f&quot;Invalid amount type for sale {record.get(&#39;sale_id&#39;, &#39;unknown&#39;)}: expected int or float, got {type(amount)}&quot;)<br>        if amount &lt; 0:<br>            raise ValueError(f&quot;Negative amount not allowed for sale {record.get(&#39;sale_id&#39;, &#39;unknown&#39;)}: got {amount}&quot;)<br>        total += float(amount)<br>        count += 1<br>    average = total / count if count &gt; 0 else 0.0<br>    return (total, average, count)</pre><h3>6. Optional[T]: Either type T or None</h3><p>Indicates a value can be of type T or None, useful for optional parameters or return values.</p><pre>from typing import List, Dict, Union, Optional<br><br>def find_customer_email(customer_id: str, customers: List[Dict[str, Union[str, int]]]) -&gt; Optional[str]:<br>    &quot;&quot;&quot;<br>    Look up a customer&#39;s email by ID from a list of customer records.<br>    Used in customer support systems, integrating with API or database data.<br>    <br>    Args:<br>        customer_id: Unique customer identifier <br>        customers: List of dictionaries, each representing a customer with fields like<br>                   &#39;id&#39; (str), &#39;name&#39; (str), &#39;email&#39; (str), and &#39;phone&#39; (int or str).<br>    Returns:<br>        Customer&#39;s email if found, else None.<br>    &quot;&quot;&quot;<br>    if not customers:<br>        return None<br>    for customer in customers:<br>        if not isinstance(customer.get(&#39;id&#39;), str):<br>            raise TypeError(f&quot;Invalid id type for customer record: expected str, got {type(customer.get(&#39;id&#39;))}&quot;)<br>        if customer.get(&#39;id&#39;) == customer_id:<br>            email = customer.get(&#39;email&#39;)<br>            if not isinstance(email, str):<br>                raise TypeError(f&quot;Invalid email type for customer {customer_id}: expected str, got {type(email)}&quot;)<br>            return email<br>    return None</pre><h3>7. Any: Any type is allowed</h3><p>A fallback when the type is unknown or unrestricted, used sparingly in production.</p><pre>from typing import Any<br><br>def log_event(event: Any, timestamp: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Log an event of any type to a monitoring system.<br>    Used for flexible logging in diagnostics and analytics.<br>    <br>    Args:<br>        event: Any event data to log (string, dict, etc.).<br>        timestamp: Time of the event in string format.<br>    &quot;&quot;&quot;<br>    print(f&quot;[{timestamp}] Event logged: {event}&quot;)</pre><h3>8. Callable[[Arg1Type, Arg2Type], Return Type]: A function with specific argument and return types</h3><p>Describes a function or callable object with typed arguments and return value.</p><pre>from typing import Callable, List, Dict, Union<br><br>def apply_discount(products: List[Dict[str, Union[int, float, str]]], discount_func: Callable[[float, str], float]) -&gt; List[Dict[str, Union[int, float, str]]]:<br>    &quot;&quot;&quot;<br>    Apply a custom discount function to product prices, considering product category.<br>    Used in pricing systems for flexible, category-based discount policies in e-commerce.<br>    <br>    Args:<br>        products: List of dictionaries, each representing a product with fields like<br>                  &#39;id&#39; (str), &#39;price&#39; (float or int), and &#39;category&#39; (str).<br>        discount_func: Function to compute discounted price based on original price and category.<br>    Returns:<br>        List of product dictionaries with updated &#39;price&#39; fields after discount.<br>    &quot;&quot;&quot;<br>    if not products:<br>        return []<br>    discounted_products = []<br>    for product in products:<br>        price = product.get(&#39;price&#39;, 0)<br>        category = product.get(&#39;category&#39;, &#39;general&#39;)<br>        if not isinstance(price, (int, float)):<br>            raise TypeError(f&quot;Invalid price type for product {product.get(&#39;id&#39;, &#39;unknown&#39;)}: expected int or float, got {type(price)}&quot;)<br>        if price &lt; 0:<br>            raise ValueError(f&quot;Negative price not allowed for product {product.get(&#39;id&#39;, &#39;unknown&#39;)}: got {price}&quot;)<br>        if not isinstance(category, str):<br>            raise TypeError(f&quot;Invalid category type for product {product.get(&#39;id&#39;, &#39;unknown&#39;)}: expected str, got {type(category)}&quot;)<br>        discounted_price = discount_func(float(price), category)<br>        updated_product = product.copy()<br>        updated_product[&#39;price&#39;] = discounted_price<br>        discounted_products.append(updated_product)<br>    return discounted_products<br><br>def category_discount(price: float, category: str) -&gt; float:<br>    &quot;&quot;&quot;Apply a discount based on price and category.&quot;&quot;&quot;<br>    if category == &quot;electronics&quot;:<br>        return price * 0.9  # 10% off for electronics<br>    return price * 0.95  # 5% off for other categories</pre><h3>Why Is Using the typing Module Important in Production Code?</h3><ul><li><strong>Improves Readability &amp; Documentation</strong>: Type hints clarify inputs and outputs, speeding up onboarding in large projects.</li><li><strong>Catches Bugs Early</strong>: Tools like mypy and Pyright detect type errors before runtime, preventing crashes.</li><li><strong>Enhances Tooling</strong>: IDEs use type hints for better autocompletion, refactoring, and error detection.</li><li><strong>Aids Code Maintenance</strong>: Ensures consistent data contracts in large codebase , reducing bugs.</li><li><strong>Supports API Stability</strong>: Makes library and API contracts clear, boosting trust and adoption.</li><li><strong>Reduces Debugging Time</strong>: Early mismatch detection cuts down production debugging efforts.</li></ul><h3>Conclusion</h3><p>The typing module is a powerful addition to Python that makes code safer, easier to understand, and more maintainable—critical factors in production environments. By embracing type hints and using static checkers, your company can reduce bugs, improve collaboration, and build scalable Python applications with confidence. For professional, reliable code that aligns with enterprise standards, integrating the typing module is a best practice worth adopting today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4113aada38a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[✨ Why Python List Comprehensions Are Slowing You Down — And What To Use Instead]]></title>
            <link>https://medium.com/@tssujith2002/why-python-list-comprehensions-are-slowing-you-down-and-what-to-use-instead-7036daa44c60?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7036daa44c60</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code-efficiency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Mon, 26 May 2025 10:48:15 GMT</pubDate>
            <atom:updated>2025-05-26T10:48:15.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>✨ Why Python List Comprehensions Are Slowing You Down — And What To Use Instead</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEcACMKuau5Uo9NDeK3AAA.png" /></figure><blockquote>Small change, big impact — optimize your Python like a pro.</blockquote><h3>🚀 Why This Article?</h3><p>Most Python developers love list comprehensions. But are you silently draining memory and slowing things down?</p><p>👉 This article will <strong>reveal how generator expressions</strong> can:</p><ul><li>🚀 Boost performance,</li><li>💾 Slash memory usage,</li><li>🏗 Make your code more scalable.</li></ul><p>Whether you’re working on data processing, pipelines, or just summing numbers, this small trick can <strong>level up your Python game</strong>.</p><p>🔍 What’s a Generator Expression?</p><p><strong>List comprehension:</strong></p><pre>[x * x for x in range(10)]</pre><p>✅ Builds a full list in memory.</p><p><strong>Generator expression:</strong></p><pre>(x * x for x in range(10))</pre><p>✅ Yields one value at a time, on demand.</p><h3>⚡ Why Should You Care?</h3><p>Imagine you have <strong>10 million numbers</strong>.</p><p>With list comprehension:</p><pre>sum([i for i in range(10_000_000)])</pre><p>⛔ Builds a massive list → consumes gigabytes of RAM.</p><p>With generator expression:</p><pre>sum(i for i in range(10_000_000))</pre><p>✅ Streams numbers → constant, tiny memory footprint.</p><h3>Benchmark Example</h3><pre>import time<br>N = 10_000_000<br>def sum_list():<br>    start = time.time()<br>    total = sum([i for i in range(N)])<br>    print(f&quot;List: {time.time() - start:.2f}s&quot;)<br>def sum_gen():<br>    start = time.time()<br>    total = sum(i for i in range(N))<br>    print(f&quot;Generator: {time.time() - start:.2f}s&quot;)<br>sum_list()<br>sum_gen()</pre><h3>Expected result:</h3><ul><li><strong>List:</strong> Higher memory, sometimes slower.</li><li><strong>Generator:</strong> Lower memory, faster start.</li></ul><h3>🏋 When to Use Generator Expressions</h3><p>✅ Passing into built-ins like sum(), max(), min().<br> ✅ Filtering or transforming data once.<br> ✅ Chaining multiple operations without storing intermediate lists.</p><p>Example:</p><pre>result = sum(x for x in data if x % 2 == 0)</pre><h3>⚠ When NOT to Use</h3><p>❌ If you need to reuse the values (generators are one-shot).<br> ❌ If you need random access like my_list[5] (generators are not indexable).</p><h3>🛠 Practical Example</h3><p>Here’s a production-ready code snippet we optimized:</p><pre>def sum_even_indices_times_last(array):<br>    if not array:<br>        return 0<br>    even_index_sum = sum(array[i] for i in range(0, len(array), 2))<br>    return even_index_sum * array[-1]</pre><p>Why is it better?</p><ul><li><strong>sum()</strong> receives a generator, not a pre-built list.</li><li><strong>Memory stays low</strong> even for massive inputs.</li></ul><h3>🔑 Takeaway</h3><p>Using a generator expression is:<br> ✅ Simple to swap in,<br> ✅ Cleaner and more Pythonic,<br> ✅ A small but powerful optimization.</p><p>If you care about <strong>speed</strong> and <strong>memory efficiency</strong>, this should be in your toolkit.</p><h3>💬 Let’s Talk!</h3><p>Have you used generator expressions before? Did they help speed up your code or avoid memory crashes?</p><p>👉 Drop your thoughts in the comments!<br> 👉 Share this with a teammate stuck in a slow, memory-hungry Python script.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7036daa44c60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking Square Root Methods and List Creation in Python: A Deep Dive]]></title>
            <link>https://medium.com/@tssujith2002/benchmarking-square-root-methods-and-list-creation-in-python-a-deep-dive-ce0a464a7f7e?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce0a464a7f7e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Sun, 25 May 2025 11:12:44 GMT</pubDate>
            <atom:updated>2025-05-25T11:12:44.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Benchmarking Square Root Methods and List Creation in Python: A Deep Dive</h3><p><em>Unlock Python’s hidden speed hacks and elevate your code performance!</em></p><p>In the world of Python, the <strong>difference between good code and great code</strong> often comes down to the tiniest details: which built-in you use, which function you call, which approach you take. Recently, I ran some <strong>hot microbenchmarks</strong> comparing three ways to calculate square roots (x ** 0.5, math.sqrt(x), pow(x, 0.5)) and two ways to create large lists (list comprehension vs list(range())).</p><p>Here’s the raw timing data that sparked some jaw-dropping insights:</p><pre>import timeit<br>import math<br><br>def benchmark_sqrt_methods():<br>    &quot;&quot;&quot;Benchmark different methods of calculating square roots.&quot;&quot;&quot;<br>    values = list(range(1, 100_001))<br>    def pow_op():<br>        for x in values:<br>            _ = x ** 0.5<br><br>    def sqrt_op():<br>        for x in values:<br>            _ = math.sqrt(x)<br><br>    def pow_func():<br>        for x in values:<br>            _ = pow(x, 0.5)<br>            <br>    runs = 100<br>    print(f&quot;x**0.5   : {timeit.timeit(pow_op,   number=runs):.4f}s&quot;)<br>    print(f&quot;math.sqrt: {timeit.timeit(sqrt_op,  number=runs):.4f}s&quot;)<br>    print(f&quot;pow(x,0.5): {timeit.timeit(pow_func, number=runs):.4f}s&quot;)<br><br>benchmark_sqrt_methods()<br><br>def benchmark_list_creation():<br>    &quot;&quot;&quot;Benchmark list creation: comprehension vs list(range).&quot;&quot;&quot;<br>    def list_comp():<br>        return [i for i in range(1, 100_001)]<br><br>    def range_list():<br>        return list(range(1, 100_001))<br><br>    runs = 100<br>    t_comp = timeit.timeit(list_comp, number=runs)<br>    t_range = timeit.timeit(range_list, number=runs)<br><br>    print(f&quot;List comprehension: {t_comp:.4f}s&quot;)<br>    print(f&quot;list(range)       : {t_range:.4f}s&quot;)<br><br>benchmark_list_creation()</pre><pre>Output:<br>x**0.5        : 0.5920s<br>math.sqrt     : 0.4316s<br>pow(x,0.5)    : 0.6868s<br>List comprehension: 0.2686s<br>list(range)        : 0.1768s</pre><p>Let’s unpack why these differences exist and <strong>how you can apply them to become a sharper, faster Python developer.</strong></p><h3>⚡ Part 1: Calculating Square Roots</h3><h4>🔹 1. math.sqrt(x) — The Speed Demon</h4><ul><li><strong>What it does:</strong> Calls the C standard library’s sqrt() function.</li><li><strong>Why it’s fast:</strong></li><li>Runs compiled machine-level code (outside Python loops).</li><li>Uses CPU-level hardware instructions.</li><li>Skips Python’s internal type juggling.</li><li><strong>When to use:</strong> Numeric-heavy code, simulations, scientific calculations — anytime speed is mission-critical.</li><li><strong>Benchmark result:</strong> <strong>Fastest.</strong></li></ul><h4>🔹 2. x ** 0.5 — The Readability Favorite</h4><ul><li><strong>What it does:</strong> Uses Python’s general exponentiation (PyNumber_Power).</li><li><strong>Why it’s slower:</strong></li><li>Handles generic powers (not just square roots).</li><li>Includes type checks, conversions, and internal math.</li><li><strong>When to use:</strong> When your focus is readability or you’re working with non-square root exponents.</li><li><strong>Benchmark result:</strong> <strong>Middle.</strong></li></ul><h4>🔹 3. pow(x, 0.5) — The Underperformer</h4><ul><li><strong>What it does:</strong> Function-call equivalent of **, with added namespace resolution.</li><li><strong>Why it’s slowest:</strong></li><li>Extra function call overhead.</li><li>More stack management.</li><li><strong>When to use:</strong> Rarely — only when you specifically need the pow function (like with three-argument versions).</li><li><strong>Benchmark result:</strong> <strong>Slowest.</strong></li></ul><p><strong>💡 Takeaway:</strong> For maximum speed, trust the power of <strong>math.sqrt()</strong>.</p><h3>⚡ Part 2: Creating Large Lists</h3><h4>🔹 1. List Comprehension [i for i in range(n)] — The Pythonic Workhorse</h4><ul><li><strong>What it does:</strong> Explicitly loops over a range, appending each item.</li><li><strong>Why it’s slower:</strong></li><li>Executes Python bytecode per iteration.</li><li>Adds Python-level append overhead.</li><li><strong>When to use:</strong> When transforming or filtering elements, not just copying.</li><li><strong>Benchmark result:</strong> <strong>Slower.</strong></li></ul><h4>🔹 2. list(range(n)) — The C-Level Rocket</h4><ul><li><strong>What it does:</strong> Converts a range object to a list in bulk at the C level.</li><li><strong>Why it’s faster:</strong></li><li>Bypasses Python loops.</li><li>Uses optimized internal conversion.</li><li><strong>When to use:</strong> Whenever you just need a list of integers.</li><li><strong>Benchmark result:</strong> <strong>Faster.</strong></li></ul><p><strong>💡 Takeaway:</strong> Skip the fancy comprehension when you just need numbers — go straight to <strong>list(range())</strong>.</p><h3>🔥 Final Recommendations</h3><p>✅ <strong>Square roots:</strong> Use math.sqrt() for best performance.</p><p>✅ <strong>Exponentiation:</strong> Stick to ** for clarity, but avoid pow() unless you need special cases.</p><p>✅ <strong>List creation:</strong> Prefer list(range()) over list comprehensions when making plain lists.</p><h3>🌟 Why This Matters</h3><p>Python often gets labeled as “slow,” but under the hood, <strong>CPython</strong> leans heavily on C libraries and hardware-level optimizations. By understanding these hidden pathways, you can:</p><ul><li>Make smarter code choices.</li><li>Optimize bottlenecks.</li><li>Write Python that punches above its weight.</li></ul><p>Stay sharp, keep experimenting, and happy benchmarking!</p><p>💥 <em>If you loved this performance deep dive, share it, bookmark it, and drop your own favorite Python speed tricks in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce0a464a7f7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Benchmarking Python: What’s the Fastest Way to Square Numbers?]]></title>
            <link>https://medium.com/@tssujith2002/benchmarking-python-whats-the-fastest-way-to-square-numbers-fa9223619c76?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa9223619c76</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Sat, 24 May 2025 13:06:00 GMT</pubDate>
            <atom:updated>2025-05-24T13:06:00.045Z</atom:updated>
            <content:encoded><![CDATA[<p>When you need to square a lot of numbers in Python, you might think:<br> “Well, I can just use pow(x, 2)… or maybe x ** 2… or wait, isn’t x * x even faster?”</p><p>These subtle choices matter, especially when you’re dealing with <strong>large datasets</strong> or performance-sensitive code. So, I decided to <strong>put them to the test</strong>.</p><p>Let’s walk through what I found.</p><p>I tested four common approaches to generate the list:</p><p><strong>Using </strong><strong>pow(x, 2) with </strong><strong>map</strong></p><pre>list(map(pow, range(limit), [2] * limit))</pre><p><strong>Using a lambda expression </strong><strong>x ** 2 with </strong><strong>map</strong></p><pre>list(map(lambda x: x**2, range(limit)))</pre><p><strong>Using list comprehension with </strong><strong>x ** 2</strong></p><pre>[x**2 for x in range(limit)]</pre><p><strong>Using list comprehension with </strong><strong>x * x</strong></p><pre>[x * x for x in range(limit)]</pre><h3>⏱️ The Benchmark Setup</h3><p>I used Python’s built-in timeit module, squaring <strong>100,000 numbers</strong> (N = 100,000) and repeating each test <strong>200 times</strong> to get reliable averages.</p><h3>📊 The Results</h3><p>Here’s how they performed on my machine:</p><p><strong>Method</strong> <strong>Time (seconds)</strong> pow(x, 2) (with map) 2.5768 s lambda x**2 (with map) 3.3433 s list comprehension x**2 2.0660 s list comprehension x * x <strong>1.5980 s</strong></p><p>🥇 <strong>Winner:</strong><br> List comprehension using x * x was the clear champion — <strong>about 1.6 seconds</strong> to square all numbers across 200 repeats, roughly <strong>40% faster</strong> than pow.</p><h3>🔍 Why Does This Happen?</h3><p>Let’s unpack it:</p><ul><li><strong>pow(x, 2)</strong><br> Python’s pow() is a general-purpose function, which handles many edge cases (like modular exponentiation) — but for the simple case of squaring, it’s overkill.</li><li><strong>x ** 2</strong><br> The ** operator is more direct but still slightly slower, especially when wrapped in a lambda and passed to map.</li><li><strong>x * x</strong><br> Multiplication is <strong>the simplest and fastest</strong> operation here. No function calls, no operator overloading, just pure arithmetic.</li><li><strong>List comprehensions vs. map:</strong><br> List comprehensions are highly optimized in CPython. They generally outperform map() when paired with lambdas, thanks to reduced function call overhead.</li></ul><h3>🧪 Validating the Output</h3><p>Of course, speed means nothing if correctness is off. I verified the first 10 outputs across all methods:</p><pre>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</pre><p>✅ They all match.</p><h3>🚀 Takeaways</h3><ul><li><strong>When performance matters:</strong> Prefer x * x over pow(x, 2) or x ** 2.</li><li><strong>For clarity:</strong> List comprehensions are often more readable and faster than map() + lambda.</li><li><strong>If you’re squaring millions of numbers in a tight loop:</strong> This choice can make a measurable difference.</li></ul><h3>🏁 Final Thoughts</h3><p>These kinds of micro-benchmarks won’t always matter for small scripts or one-off tasks. But when scaling up or writing performance-critical code, <strong>tiny optimizations add up</strong>.</p><p>I encourage you to experiment! Try other operations, different data sizes, or even run this benchmark on PyPy or another Python interpreter — you might be surprised at the differences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa9223619c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Singly Linked Lists in Python ]]></title>
            <link>https://medium.com/@tssujith2002/a-beginners-guide-to-singly-linked-lists-in-python-96c35d62b8f1?source=rss-cbee294ca0e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c35d62b8f1</guid>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[linked-list-operations]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[sujith t s]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 09:37:17 GMT</pubDate>
            <atom:updated>2024-09-18T09:37:17.750Z</atom:updated>
            <content:encoded><![CDATA[<p>Singly Linked Lists (SLL) are a fundamental data structure that plays a key role in computer science. In a linked list, each element is a separate object referred to as a node, and the list consists of a sequence of nodes. Each node contains two parts: the data and a reference to the next node in the sequence.</p><p>In this article, we will explore how to create a singly linked list in Python, covering essential operations such as insertion, deletion, and traversal. Let’s get started by implementing a singly linked list from scratch.</p><h3>What is a Singly Linked List?</h3><p>A <strong>Singly Linked List</strong> is a type of linear data structure where each element points to the next element in the list, forming a sequence of nodes. Each node has:</p><ul><li><strong>data</strong>: The value stored in the node.</li><li><strong>next</strong>: A reference (or pointer) to the next node in the list.</li></ul><p>Here’s a simple diagram of a singly linked list:</p><pre>[Node1 | next] -&gt; [Node2 | next] -&gt; [Node3 | next] -&gt; None<br></pre><p>Unlike arrays, linked lists do not require contiguous memory allocation, making them more flexible but slightly more complex to manipulate.</p><h3>Implementing a Singly Linked List in Python</h3><p>We will break down the linked list into two main classes:</p><ol><li><strong>Node</strong>: Represents each element of the linked list.</li><li><strong>LinkedList</strong>: Manages the overall list and performs operations like insertion, deletion, and traversal.</li></ol><pre># Node class to represent each element in the linked list<br>class Node:<br>    def __init__(self, data):<br>        self.data = data  # Stores data<br>        self.next = None  # Points to the next node<br><br># LinkedList class to handle operations on the linked list<br>class LinkedList:<br>    def __init__(self):<br>        self.head = None  # Points to the first node in the list</pre><h3>Insertion Operations</h3><ol><li><strong>Insert at the front</strong>: We create a new node and point its next to the current head of the list. The new node becomes the head.</li></ol><pre>def insert_front(self, data):<br> new_node = Node(data)<br> new_node.next = self.head<br> self.head = new_node<br><br>ll = LinkedList()<br>ll.insert_front(10)<br>ll.insert_front(20)<br>ll.insert_front(30)<br>ll.printlist()  # Output: 30 -&gt; 20 -&gt; 10 -&gt; None</pre><p><strong>2. Insert at the end</strong>: If the list is empty, the new node becomes the head. Otherwise, we traverse to the end of the list and append the new node.</p><pre>def insert_end(self, data):<br>    new_node = Node(data)<br>    if self.head is None:<br>        self.head = new_node<br>        return<br>    last = self.head<br>    while last.next:<br>        last = last.next<br>    last.next = new_node<br><br>ll.insert_end(40)<br>ll.printlist()  # Output: 30 -&gt; 20 -&gt; 10 -&gt; 40 -&gt; None</pre><p><strong>3.Insert at a specific position</strong>: This allows insertion at any valid position in the list. We traverse the list until the desired position and update the pointers accordingly.</p><pre>def insert_at_position(self, position, data):<br>    if position &lt; 1:<br>        print(&quot;Invalid position&quot;)<br>        return<br>    if position == 1:<br>        self.insert_front(data)<br>        return<br>    new_node = Node(data)<br>    cur_node = self.head<br>    for _ in range(1, position - 1):<br>        if cur_node is None:<br>            print(&quot;Invalid position&quot;)<br>            return<br>        cur_node = cur_node.next<br>    new_node.next = cur_node.next<br>    cur_node.next = new_node</pre><h3>Deletion Operations</h3><ol><li><strong>Delete from the front</strong>: Simply move the head pointer to the next node.</li></ol><pre>def delete_front(self):<br>    if self.head is None:<br>        return<br>    self.head = self.head.next<br></pre><p><strong>2. Delete from the end</strong>: We need to traverse the list and find the second last node to set its next to None.</p><pre>def delete_end(self):<br>    if self.head is None:<br>        return<br>    if self.head.next is None:<br>        self.head = None<br>        return<br>    temp = self.head<br>    while temp.next.next:<br>        temp = temp.next<br>    temp.next = None</pre><p><strong>3. Delete a specific node by value</strong>: Traverse the list to find the node with the given key and update the pointers to remove the node.</p><pre>def delete_node(self, key):<br>    if self.head is None:<br>        return<br>    if self.head.data == key:<br>        self.head = self.head.next<br>        return<br>    last = self.head<br>    while last.next:<br>        if last.next.data == key:<br>            last.next = last.next.next<br>            return<br>        last = last.next</pre><h3>Traversing the List</h3><p>To print all elements in the list, we can traverse the list from the head to</p><pre>def printlist(self):<br>    temp = self.head<br>    while temp:<br>        print(temp.data, end=&quot; -&gt; &quot;)<br>        temp = temp.next<br>    print(&quot;None&quot;)</pre><h3>Example Usage</h3><p>Here’s how you can use the above operations:</p><pre>ll = LinkedList()<br><br>ll.insert_front(10)<br>ll.insert_front(20)<br>ll.insert_front(30)<br>ll.printlist()  # Output: 30 -&gt; 20 -&gt; 10 -&gt; None<br><br>ll.insert_end(40)<br>ll.printlist()  # Output: 30 -&gt; 20 -&gt; 10 -&gt; 40 -&gt; None<br><br>ll.insert_at_position(2, 100)<br>ll.printlist()  # Output: 30 -&gt; 100 -&gt; 20 -&gt; 10 -&gt; 40 -&gt; None<br><br>ll.delete_front()<br>ll.printlist()  # Output: 100 -&gt; 20 -&gt; 10 -&gt; 40 -&gt; None<br><br>ll.delete_end()<br>ll.printlist()  # Output: 100 -&gt; 20 -&gt; 10 -&gt; None</pre><h3>Time Complexity of Operations</h3><ul><li><strong>Insertion (front)</strong>: O(1)</li><li><strong>Insertion (end)</strong>: O(n)</li><li><strong>Insertion (at position)</strong>: O(n)</li><li><strong>Deletion (front)</strong>: O(1)</li><li><strong>Deletion (end)</strong>: O(n)</li><li><strong>Traversal</strong>: O(n)</li></ul><p>Singly linked lists offer flexibility in memory usage, making them suitable for dynamic data structures where elements need to be inserted or deleted frequently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c35d62b8f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>