<?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[Coder’s Handbook - Medium]]></title>
        <description><![CDATA[Useful tips regarding programming languages and technologies - Medium]]></description>
        <link>https://medium.com/coders-handbook?source=rss----518a7aa0849---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Coder’s Handbook - Medium</title>
            <link>https://medium.com/coders-handbook?source=rss----518a7aa0849---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:15:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/coders-handbook" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Linear and Logisitic Regression]]></title>
            <link>https://medium.com/coders-handbook/linear-and-logisitic-regression-8a6c366809f8?source=rss----518a7aa0849---4</link>
            <guid isPermaLink="false">https://medium.com/p/8a6c366809f8</guid>
            <dc:creator><![CDATA[Stefano Lia]]></dc:creator>
            <pubDate>Thu, 21 May 2026 04:01:00 GMT</pubDate>
            <atom:updated>2026-05-21T04:01:00.576Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Simple Introduction to the Basics of Data Science</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X17D8AcNwri3uZhs7vEy3w.jpeg" /><figcaption>Image generated with AI</figcaption></figure><h3>Linear Regression</h3><p>Linear regression is often the first method you encounter when you start studying machine learning. Some people think that, since you can calculate the best coefficients that approximate the dataset, it is somehow different than other machine learning algorithms that rely on more sophisticated approaches such as gradient descent.</p><p>Let’s see why that’s not the case.</p><p>The first thing to do in Machine Learning, after you choose the algorithm to use, is to choose an appropriate loss function. In the case of linear regression, the most common one is the <strong>squared loss</strong>, which is the squared error of the residuals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*qTqkwPMMLI-kMS56A1-2OQ.png" /><figcaption>Typical Loss Function for Linear Regression</figcaption></figure><p>The squared loss is also the basis of the evaluation metric called MSE (Mean Squared Error).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*AaRaqtiBn82B-ZMrLGrTUQ.png" /><figcaption>Typical Evaluation Metric for Linear Regression</figcaption></figure><p>The squared loss is the objective function we minimize in linear regression to fit the best linear relationship between the independent variables and the dependent variable. MSE, on the other hand, is an evaluation metric derived from the same principle: it measures the average squared error of the model. Those are two different concepts, even if they are related.</p><p>The regression method that minimizes the sum of squared residuals is called <strong>Ordinary Least Squares (OLS)</strong>. It is a closed-form solution, meaning we can compute the optimal coefficients directly using a formula instead of relying on iterative methods like gradient descent.</p><p>Under ideal conditions, OLS has a single global solution because the squared-error objective is <strong>convex</strong>. More precisely, when the input features are linearly independent (one of the assumptions of Linear Regression), the solution is unique, and the global minimum corresponds to the unique local minimum of the convex function.</p><p>Because OLS is so efficient, some people think linear regression is fundamentally different from other machine learning methods, such as decision trees, random forests, or SVMs. That’s misleading. OLS is just the optimization method commonly used for this model. We could use gradient descent for linear regression as well, but in this case, it is usually less computationally convenient.</p><h4>Assumptions of Linear Regression</h4><ul><li><strong>Linearity</strong>: the relationship between the dependent variable and the independent variables must be linear</li><li><strong>Independence</strong>: the predictors must be all linearly independent; otherwise, there is no single solution for the coefficients, and during training, there is numerical instability. <br>Also, the errors should be uncorrelated with each other, something that doesn’t happen in time series. OLS linear regression assumes the residuals are independent across observations so that the model can separate signal from noise correctly.</li><li><strong>Normality</strong>: the residuals are normally distributed. While this assumption is not necessary for obtaining unbiased coefficient estimates, it is important for hypothesis testing and constructing confidence intervals. In addition, when the errors are normally distributed, the ordinary least squares estimator is equivalent to the maximum likelihood estimator.</li><li><strong>Errors must have constant variance (homoscedasticity)</strong>: the variance of the errors remains constant regardless of the values of the independent variables. Unfortunately, these assumptions in real-world scenarios don’t hold. Without this condition, there are incorrect standard errors that are used to quantify the uncertainty around the coefficient estimates.</li></ul><p>You can remember these assumptions with the acronym <strong>LINE</strong>.</p><p>In my experience, linearity and lack of strong multicollinearity matter most for prediction. The other assumptions mainly affect inference (p-values, confidence intervals).</p><h4>How to Evaluate a Linear Regression Model</h4><p>We have seen the assumptions and loss function to optimize (and how) in a linear regression model. Now we need to see how to evaluate it.</p><p><strong>RMSE (Root Mean Squared Error) — How bad are the misses?</strong></p><ul><li>It is the square root of the Mean Squared Error</li><li>Same unit as the target</li><li>By squaring the errors before averaging, RMSE emphasizes larger errors. So, it is sensitive to large outliers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*jCPNSs_zeiZMTaTcuPB-gA.png" /></figure><p><strong>MAE (Mean Absolute Error) — What is the typical miss?</strong></p><ul><li>Average magnitude of the errors</li><li>Same unit as the target, but dependent on the scale of the target variable</li><li>It doesn’t align with the least squares objective function commonly used in regression training</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*TYmQn6LdAFSEduQSf0XghA.png" /></figure><p>RMSE and MAE weigh errors differently: MAE treats every unit of error linearly, while RMSE penalizes big errors harder.</p><p>If your errors are mostly small but you care about avoiding occasional large mistakes, RMSE is useful; however, if your data has real outliers and you want a more stable summary of the typical error, MAE is usually better.</p><h4>R2 Score</h4><ul><li>Also called the Coefficient of Determination.</li><li>It measures the quality of the fit by comparing the model’s errors against those of a baseline model that always predicts the mean target value for all inputs.</li><li>Or it measures the strength of the relationship between the model and the target variable.</li><li>Scale independent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*5V3VFKnA8kxVhA74O9r3QA.png" /></figure><ul><li>R2 = 1: the numerator is 0, which means your model makes perfect predictions</li><li>R2 &lt; 0: your model performs worse than the average one</li><li>R2 = 0: your model performs like the average one</li></ul><p>R2 can be artificially inflated by adding more predictors to the model, even though these predictors do not contribute meaningfully to its predictive power. So, it’s better to use the adjusted R2 score, which penalizes R2 based on the number of predictors in the model.</p><h3>Logistic Regression</h3><p>Logistic regression is the cousin of linear regression, but it is used to predict a <strong>category</strong> rather than a number, such as spam vs. not spam or yes vs. no.</p><p>To make a classification decision, we usually choose a decision threshold, often 0.5. If the predicted probability is above 0.5, we classify the case as positive; if it is below 0.5, we classify it as negative.</p><h4>How Can We Express Probability?</h4><p>What is the probability that one event will happen? We usually express this probability as <em>p</em>, and it is a number between 0 and 1. But it’s not the only way. We can also use the concept of odds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*qUnlQyul04em0Jnv6VVRCA.png" /></figure><p>For example, if the probability is 0.75, the odds are 3, which means that the event is 3 times more likely to occur than not occur. We use odds because now the probability is expressed in another range [0, +∞). But to fit a linear model, we take the logarithm of the formula, which transforms the range to (-∞, +∞). This gives us the <strong>log-odds</strong>, or <strong>logit</strong>.</p><p>The key idea is that logistic regression represents the log-odds of the target being in the positive class as a linear combination of the input features. The unbounded scale can then be modeled as a <strong>linear combination</strong> of predictors, which is exactly what logistic regression does.</p><p>To convert the log-odds back into probabilities, logistic regression uses the sigmoid function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*LZpc6gRjEA6uTjPTqqmWxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*6vcroLRJj2S9eJNrLhx98g.png" /></figure><p>The sigmoid function is the inverse of the logit function. It takes any real number and squeezes it into an interval from 0 to 1, which makes it perfect for probability prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*lMaP_e2S7bJ7sWx_Ig1MNQ.png" /></figure><h4>Decision Boundaries</h4><p>When we deal with logistic regression, the decision boundaries are the points where the equation wT * x + b = 0, which means when the sigmoid of the logit is equal to 0.5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*6Z3D8sNbzTA4RS0kwnin1A.png" /></figure><p>In other words, it is a set of points in the feature space where a model assigns equal probability or score to two or more classes. These points define a hyperplane in the feature space, orthogonal to the weights. Two vectors are <strong>orthogonal</strong> (i.e., at 90°, or “perpendicular”) <strong>if and only if their dot product is zero</strong> (assuming they’re not the zero vector)</p><p>The linearity of this boundary makes the logistic regression a linear classifier.</p><h4>Training a Logistic Regression Model</h4><p>When we train a linear regression, we are trying to find the “best-fit” line that comes as close as possible to all the points on average (minimizing the squared error); instead, when we train a logistic regression model, we want to find the best parameter vector (W) such that the predicted probabilities match the true labels y as closely as possible.</p><p>For this purpose, we need a loss function. The simplest you can think of in this case is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*iC_QArpmOxx2PszXFYSogQ.png" /></figure><p>However, the 0–1 loss is not differentiable. In Logistic Regression, we use the gradient descent algorithm to learn from the data, which requires a differentiable objective. It also ignores probabilities, so we miss the information on how confident the model was.</p><p>What about the Squared Loss?</p><p>Squared loss “assumes” normal errors because <strong>minimizing squared error is mathematically equivalent to maximizing the likelihood when the errors are Gaussian</strong>. This distribution doesn’t hold in our case because our target is discrete (0, 1).</p><p>Instead, we use <strong>log loss</strong>, also called <strong>negative log-likelihood</strong>, as the cost function. Negative log‑likelihood is a very common way to define loss functions in machine learning, especially when we have a <strong>probabilistic model</strong> for the target variable.</p><p>In the case of binary classification, we model the target Y as a <strong>Bernoulli random variable</strong>:</p><ul><li>It takes the value 1 with probability</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*3OcNp5wZufsmBU_RyRBbTg.png" /></figure><ul><li>and the value 0 with probability 1-p</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*_E6jwHK98l3wxFEEr11iIw.png" /><figcaption>Log Likelihood in the Binary Case</figcaption></figure><p>The <strong>log‑likelihood </strong>of the dataset is the sum of the log probabilities of the observed labels under the Bernoulli model. The loss is the negative of that log-likelihood, so minimizing it is the same as maximizing the likelihood of the data.</p><p>To minimize the negative log-likelihood, we use the <strong>gradient descent algorithm.</strong></p><h4>Notes on Negative Log-Likelihood</h4><p>When we do Machine Learning, we should wonder how we ended up using the negative log-likelihood as the cost function. The likelihood is a very common way to define an optimization problem, or better, to turn probabilistic modeling into a clean optimization problem.</p><p>When we assume a probabilistic model for the target given the dataset, such as Bernoulli for binary classification or multinomial for multi-class classification, <strong>the likelihood is the probability of observing the actual labels under that model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*8rcoQtYoVqRN04mpFlRm6g.png" /><figcaption>Likelihood expressed with probabilities</figcaption></figure><p>The likelihood of a dataset is a product of many probabilities. This product can become extremely small, causing numerical issues. So, we transform it by taking the logarithm, transforming the product to a sum for the property of the logarithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*-rs-jFHh0IkWEJAP9YTS4w.png" /><figcaption>Log likelihood</figcaption></figure><p>What we want is to maximize the likelihood, but since most optimization problems are built to minimize a loss rather than maximize the likelihood, we take the negative log-likelihood. That gives us a loss function where lower values are better:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*TKXKBbiP3Sc9KrrGSMbbHg.png" /><figcaption>Negative log likelihood</figcaption></figure><p>In classification, cross-entropy loss is equivalent to negative log-likelihood. More precisely, if the true labels are 1 or 0, then minimizing cross-entropy is the same as minimizing the negative log-likelihood of the correct class.</p><p>So, for binary classification problems, we use cross-entropy loss because it is differentiable and because minimizing it is equivalent to maximizing the likelihood of the data.</p><h4>Classification Evaluation Metrics</h4><p>The typical evaluation metric for logistic regression is accuracy, which is basically how many instances you get correct between positive and negative. The problem is that many classification problems involve imbalanced datasets, and accuracy can be misleading in these cases.</p><p>For example, if you have a detection dataset that has only 1% of fraudulent cases fraudolent, a naive model that always predicts non-fraudulent cases would have 99% of accuracy.</p><h4>Precision</h4><p>Precision measures the accuracy of the positive predictions made by the model. My interpretation is “how many True Positive examples can we predict among all the positives of the model?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*jrTwf3xyHvTyxJM61s-pXQ.png" /></figure><h4>Recall</h4><p>Recall, also known as sensitivity or true positive rate, measures the model’s ability to correctly identify all the actual positive cases. My interpretation is “how many True Positives the model predicts among all the total positives in the dataset?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*0jeksd6XUu866NN87E5AkQ.png" /></figure><p>It is usually a trade-off: when you train a model, you must decide if you want to minimize the false positives (you want to make positive classifications only when there is strong evidence — increasing precision), or to minimize the false negatives (you make positive classifications even with weak evidence — increasing recall because you do fewer negative predictions).</p><p>Models with high precision and low recall are conservative, while low precision and high recall are liberal.<br>To compare two different models with one single metric, you can use the F1 score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*pf5dDQYEgRrKXHan3oEe6Q.png" /></figure><p>Both precision and recall must be reasonably high for the F1 score to be high.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a6c366809f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coders-handbook/linear-and-logisitic-regression-8a6c366809f8">Linear and Logisitic Regression</a> was originally published in <a href="https://medium.com/coders-handbook">Coder’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures in Python]]></title>
            <link>https://medium.com/coders-handbook/data-structures-in-python-0847ad602198?source=rss----518a7aa0849---4</link>
            <guid isPermaLink="false">https://medium.com/p/0847ad602198</guid>
            <dc:creator><![CDATA[Stefano Lia]]></dc:creator>
            <pubDate>Thu, 14 May 2026 04:01:03 GMT</pubDate>
            <atom:updated>2026-05-14T04:01:03.137Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A Practical Guide to the Most Common Structures and Their Implementations</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0NgQ0EyKU2Ib1mjiWpuhQ.jpeg" /><figcaption>Image generated with AI</figcaption></figure><p>Choosing the right data structures is usually one of the keys to a good algorithm approach.</p><h3>Array-Based Sequences — Centralized Versions of Lists</h3><p>In Python, we consider list, tuples, and string classes as array-based sequences. They use indexing to access an individual element of the sequence. These are the most used classes when you code in Python, but they hide subtle details.</p><h4>Low-Level Arrays</h4><p>The primary memory of a computer is composed of bits of information grouped into larger units called bytes (8 bits). To keep track of what information is stored in what byte, the computer uses an abstraction known as a memory address. Each byte of memory is associated with a unique number that serves as its address.</p><p>Any byte of the RAM can be efficiently accessed based on its address. And we call an ARRAY a group of variables stored one after another in a contiguous portion of the computer’s memory.</p><p>A caveat of this representation is that <strong>each cell must use the same number of bytes</strong>.</p><p>Strings are a sequence of characters. Each character is Unicode in Python, which is 2 bytes. So, 6 characters are 12 bytes of memory.</p><p>A list of strings instead is saved using an internal storage mechanism of an array of object references, which is 64 bits per address. Saving the reference instead of the string avoids memory waste for saving strings directly.</p><h4>Compact Arrays in Python</h4><p><strong>Strings</strong> are an array of characters, not an array of references, which makes them a <strong>compact array</strong>.</p><p>Compact arrays have several advantages over referential structures in terms of computing performance:</p><ul><li><strong>Lower memory usage</strong>: 64 bits (8 bytes) for a reference; 2 bytes for a Unicode character.</li><li><strong>High-performance computing</strong>: the primary data are stored consecutively in memory, which makes them more performant.</li></ul><p>You can use the module array to create compact arrays, but whenever you use it, you need to define the type code:</p><pre>compact_array = array(&#39;i&#39;, [1, 2, 3, 4])</pre><p>In this case, the type code ‘i’ designates an array of (signed) integers, typically represented using at least 16 bits.</p><h4>Dynamic Arrays and Amortization</h4><p>When we create a low-level array, the computer must declare explicitly its size to properly allocate a consecutive piece of memory for its storage.</p><p>Since the system might dedicate neighboring memory locations to store other data, the capacity of an array cannot be trivially increased by expanding into subsequent cells.</p><p>This problem doesn’t affect str and tuple types because they are immutable; so, once they are created, they cannot change in size.</p><p>We say that the list represents an abstraction called a <strong>dynamic array</strong>:</p><ul><li>The user creates a list of 10 elements</li><li>The system reserves more space, predicting that the user may append new values</li><li>Eventually, the extra space reserved will be exhausted</li><li>In the latter case, the class will request a new, larger array from the system elsewhere in the memory</li></ul><h4>Efficiency of the Python’s Sequence Types</h4><ul><li>Len(data): O(1)</li><li>data[j]: O(1)</li><li>data.count(value): O(n)</li><li>data.index(value): O(k+1)</li><li>data.append(value): O(1) amortized. Ω(n) when resized</li><li>data.pop(): O(1) amortized. Omega(n) when resized</li><li>data.pop(k): O(n-k) amortized because of finding the value and then shifting. Ω(n) when pop(0)</li><li>remove(value): Ω(n). We cannot use the index to access the memory directly, so we need to find the value first and then shift the remaining elements</li><li>list1.extend(list2): O(m) if list2 has m elements. Also, here the list1 may be resized.</li></ul><h3>Stacks, Queues, and Deques</h3><h4>Stacks</h4><p>Stacks represent a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle. You can imagine the stack of plates in a cafeteria that must be cleaned.</p><p>Stacks are the simplest of all data structures, yet they are also among the most important ones.</p><p><strong>Abstract type:</strong></p><ul><li>s.push(e): add element on top of the stack</li><li>s.pop(): remove and return the top element from the stack s</li><li>s.top(): return a reference to the top element of stack s</li><li>s.is_empty(): True when s is empty</li><li>len(s): returns the number of elements</li></ul><p>You can easily implement a stack in Python using the list data structure:</p><p><strong>Implementation &amp; Time Efficiency:</strong></p><ul><li>s.push(e): l.append(e). O(1) amortized</li><li>s.pop(): l.pop(). O(1) amortized</li><li>s.top(): l[-1]. O(1)</li><li>s.is_empty(): len(s) == 0. O(1)</li><li>len(s) = len(L). O(1)</li></ul><p>We can avoid amortization if we define the maximum capacity of a stack.</p><h4>When you should use them</h4><ul><li>Matching parentheses and HTML tags</li><li>Matching tags in a Markup Language</li></ul><h4>Queues</h4><p>A queue is the closest cousin of the stack. Queues are collections of objects that are inserted according to the first-in, first-out (FIFO) principle. To understand this concept, you can imagine the line of people waiting to enter a museum.</p><p><strong>Abstract type:</strong></p><ul><li>Q.enqueue(e)</li><li>Q.dequeue()</li><li>Q.first()</li><li>Q.is_empty()</li><li>len(Q)</li></ul><p><strong>Array-Based Queue Implementation:</strong></p><p>To implement a queue efficiently using a list, we should avoid using pop(0) for the dequeue() method, since it has Ω(n) time complexity due to element shifting.</p><p>Instead, we can save in the class an index that tracks the front of the queue: when we enqueue an element, we would append it to the list as usual; when we dequeue, we would return the element at the front index, set that position to None to avoid resizing and finally increment the front index.</p><p>After a while, this approach can leave many None values at the beginning of the list, wasting space. To improve this, we can reuse those empty slots instead of always appending new elements. In this case, we would have a <strong>circular array</strong>.</p><p><strong>Time Efficiency:</strong></p><p>Q.enqueue(e): O(1) amortizied</p><p>Q.dequeue(): O(1) amortized</p><p>Q.first(): O(1)</p><p>Q.is_empty(): O(1)</p><p>len(Q): O(1)</p><p>Related to queues, there are several similar data structures:</p><ul><li><strong>Double-Ended Queues</strong>: They support insertion and deletion at both the front and back of the queue.</li><li><strong>Priority Queues</strong>: A priority queue serves the item with the highest priority first, so arrival order does not matter. If two elements have the same priority, they are typically served in insertion order.</li></ul><p>In Python, it’s very common to use the <em>collections.deque</em> package because of its efficiency. It is implemented as a <strong>double‑ended queue backed by a doubly‑linked list</strong>, which allows fast insertions and deletions from both ends.</p><p>Stack with deque package:</p><pre>from collections import deque<br><br>stack = deque()<br>stack.append(&quot;a&quot;)      # push<br>stack.append(&quot;b&quot;)<br>print(stack.pop())     # &quot;b&quot; (top)<br>print(stack.pop())     # &quot;a&quot;</pre><p>Queue with deque package:</p><pre>from collections import deque<br><br>queue = deque()<br>queue.append(&quot;a&quot;)        # enqueue at right<br>queue.append(&quot;b&quot;)<br>print(queue.popleft())   # &quot;a&quot; (front)<br>print(queue.popleft())   # &quot;b&quot;</pre><h3>Linked Lists — Distributed Representation of Lists</h3><p>The Python list class is the most common and a great choice for storage, but we saw that it has disadvantages. It uses a contiguous memory layout, which can make certain operations costly.</p><p><strong>An array provides a centralized representation of a list</strong>; alternatively, linked lists ensure a distributed representation of the collection using lightweight objects called “nodes”. Each node maintains a reference to its element and one or more references to neighboring nodes.</p><p>Unlike arrays, linked lists do not support efficient access by index</p><p>k since elements must be reached by traversing the list. However, we don’t have the problem of increasing the space when the list reaches its limit.</p><p>To add an element, we update the next reference of the last node so that it points to the new node. So, it’s all about managing the references.</p><p>This structure is useful in real-time systems where predictable operation time is critical, and amortized costs (like occasional expensive resizes) are not acceptable.</p><h4>Singly Linked Lists</h4><p>A singly linked list is a collection of nodes that collectively form a linear sequence. Each node stores an element and a reference to the next node in the list.</p><p>The first and last nodes of a linked list are known as the head and tail of the list. It is possible to reach the tail by traversing the list from the head, but it’s a common optimization to store a direct reference to it.</p><p>How does performance change when we implement stacks and queues using a singly linked list?</p><p><strong>Stack with single linked list:</strong></p><ul><li>S.push(e): O(1)</li><li>S.pop(): O(1)</li><li>S.top(): O(1)</li><li>len(S): O(1) if you save the size of the list in the class and you mantain it every time you add or remove an element</li><li>S.is_empty(): O(1)</li></ul><p><strong>Queue with single linked list:</strong> also here all the operations are O(1)</p><p>Generally, linked lists provide a clean and flexible way to implement stacks and queues. However, array elements are contiguous: the CPU prefetches them efficiently; linked‑list nodes are scattered, causing more cache misses.</p><p>As a result, a well-implemented stack or queue using an array is often faster in practice than one based on a linked list. It’s a typical trade-off between simplicity and performance.</p><h4>Circular Linked Lists</h4><p>Circularly Linked Lists are linked lists in which the tail node points back to the head, forming a loop.</p><p>Circular Linked Lists are useful when you need to implement a round-robin mechanism (e.g. allocate CPU for a set of applications). Since the last node links back to the first, you can keep moving forward without explicitly restarting from the head.</p><p>When we compare this structure to a circular array (we saw it before — where “deleted” elements are often marked as None), a circular linked list avoids wasted slots entirely. Every node represents a valid element, and we would never need to check if the element is None.</p><h4>Doubly Linked Lists</h4><p>In a doubly linked list, each node stores references to both the next node and the previous one.</p><p>This extra reference slightly increases memory usage, but it improves the performance of the deletion and insertion of an element.</p><p>Imagine you want to delete the tail of the list using single-linked lists (which means changing the next reference of the previous to None). In this case, we would need to traverse the whole linked list to get the correct reference. In a doubly linked list, you can directly access the previous node and update its reference, avoiding that traversal.</p><h3>Link-Based vs Array-Based Sequences</h3><p><strong>Array-Based Sequences:</strong></p><ul><li>They use less memory.</li><li>O(1) time access to an element based on an integer index.</li><li>Operations with equivalent asymptotic bounds typically run a constant factor more efficiently than linked-based structures.</li></ul><p><strong>Link-Based Sequences:</strong></p><ul><li>Provide a clear worst-case time bounds (not amortized) for their operations.</li><li>Can support O(1)-time insertions and deletions at arbitrary positions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0847ad602198" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coders-handbook/data-structures-in-python-0847ad602198">Data Structures in Python</a> was originally published in <a href="https://medium.com/coders-handbook">Coder’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency & Parallelism in Python]]></title>
            <link>https://medium.com/coders-handbook/concurrency-parallelism-in-python-6873e1231c84?source=rss----518a7aa0849---4</link>
            <guid isPermaLink="false">https://medium.com/p/6873e1231c84</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[parallel-programming]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Stefano Lia]]></dc:creator>
            <pubDate>Thu, 07 May 2026 04:01:01 GMT</pubDate>
            <atom:updated>2026-05-07T04:01:01.307Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why async is better?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oopUm5S5YNpr3_oWggNjIQ.jpeg" /><figcaption>Image generated by AI</figcaption></figure><p>Some notes to clear the air about the difference between concurrency and parallelism, and how to achieve it in Python.</p><h3>Python Coder’s Definitions for Concurrency and Parallelism</h3><ul><li><strong>Concurrency</strong>: handles multiple pending tasks with a single-core CPU.</li><li><strong>Parallelism</strong>: execute multiple computations at the same time. We can have: a multicore CPU, multiple CPUs, a GPU, or multiple computers in a cluster.</li><li><strong>Execution unit</strong>: objects that execute code concurrently, each with an independent state and call stack. In Python, we have processes, threads, and coroutines.</li><li><strong>Process</strong>: a program instance while it’s running, using memory and CPU. A process can span subprocesses, and they all can communicate via pipes, sockets, or memory. In Python, an object can be passed from one process to another, but it has to be <em>serializable</em>.</li><li><strong>Thread</strong>: an execution unit within a single process. When the Python process starts, it uses a single thread: the main thread. A process can create more threads to operate concurrently, and they all share the same memory space. Shared memory space can lead to corrupted data. In general, a thread consumes fewer resources than a process doing the same job.</li><li><strong>Coroutine</strong>: it’s a function that can suspend itself and resume later. In Python, they are defined with “async def”. All coroutines run within a single thread under the supervision of an event loop, which also runs in the same thread. Using frameworks such as asyncio, curio, or trio, you can achieve <em>cooperative multitasking</em>: each coroutine cedes control to another using the <em>yield </em>or <em>await </em>keyword, so another one can proceed concurrently (but not in parallel). Any blocking code in the coroutine blocks the others. In general, a coroutine consumes fewer resources than a thread doing the same job.</li><li><strong>Queue</strong>: it is a FIFO order (usually) data structure used to exchange application data and control messages. We can also have LIFO or Priority queues.</li><li><strong>Lock</strong>: It is an object that an execution unit can use to sync its actions and avoid corrupting data. The simplest type of lock is known as <em>a mutex </em>(for mutual exclusion).</li><li><strong>Contention</strong>:<strong> </strong>dispute over a limited asset or shared resource.</li></ul><h3>Python’s GIL</h3><p>Each instance of the Python interpreter is a process. You can start additional Python processes using multiprocessing or cuncurrent.futures libraries (for threads you can use cuncurrent.futures or threading).</p><p>The Python interpreter uses a single thread to run the user’s program and the memory garbage collector. Access to the interpreter state is controlled by a lock — the global interpreter lock (GIL).</p><p>Only one Python thread can hold the GIL at any time, which means that only one thread can execute Python code at any time, regardless of the number of CPU cores. To prevent a Python thread from holding the GIL indefinitely, when you do multithreading, the interpreter pauses the current thread every 5ms, releasing the GIL. At that point, the OS scheduler will pick the next thread to execute.</p><p>When we write Python code, we have no control over the GIL, but there are ways to overcome this limitation: any built-in function or any extension written in C (NumPy, SciPy) can release the GIL, or all functions that perform Disk or Network I/O.</p><p>Since one thread must hold the GIL to run, compute-intensive tasks must run in a single-threaded sequential code because using multithreading would cause the context switch every 5ms, and this overhead would kill performance instead of increasing it. To run CPU-intensive Python code on multiple cores, you must use multiple Python processes.</p><p><em>Note</em></p><p><em>Python is the language. CPython is the interpreter written in C that reads .py files, compiles them to bytecode, runs them, manages memory, implements the GIL, etc…</em></p><h3>A Concurrent Program</h3><p>Let’s imagine that we want to write a concurrent program in Python.</p><pre>def do_work(name, duration=1):<br>    &quot;&quot;&quot;<br>    Simple blocking function that simulates I/O work by sleeping.<br><br>    This is the function we&#39;ll run:<br>    - in multiple threads<br>    - in multiple processes<br>    - wrapped for asyncio (via to_thread / process pool if wanted)<br>    &quot;&quot;&quot;<br>    print(f&quot;[{name}] start&quot;)<br>    time.sleep(duration)  # simulate blocking I/O or slow operation<br>    print(f&quot;[{name}] end&quot;)</pre><h4>With Threads</h4><p>When we use threading.Thread(target=&lt;function&gt;, args=()), the argument function will run in a separate thread. You can use threading.Event() to communicate to the second thread to stop its run.</p><pre>def run_with_threads():<br>    &quot;&quot;&quot;<br>    Run several copies of do_work concurrently using threads.<br><br>    Threads share memory with the main process and all run in the same process,<br>    but can overlap while waiting on I/O.<br>    &quot;&quot;&quot;<br>    threads = []<br><br>    # Create 5 threads, each running do_work with a different name.<br>    for i in range(5):<br>        t = threading.Thread(target=do_work, args=(f&quot;thread-{i}&quot;, 1))<br>        threads.append(t)<br><br>    # Start all threads: they begin executing do_work &quot;at the same time&quot;.<br>    for t in threads:<br>        t.start()<br><br>    # Wait for all threads to finish before leaving the function.<br>    for t in threads:<br>        t.join()</pre><h4>With Processes</h4><p>When you spawn a new process, you start the whole Python interpreter (with its own GIL) as a child process in the background. So, you can easily use all available CPU cores. You can spawn a new process in the Python code using multiprocessing.Process(target=&lt;function&gt;, args=()).</p><p>Processes are isolated, so the challenge here is to make them communicate, but you can still use multiprocessing.Event().</p><pre>def run_with_processes():<br>    &quot;&quot;&quot;<br>    Run several copies of do_work concurrently using processes.<br><br>    Each process has its own Python interpreter and memory space.<br>    This can bypass the GIL and is better for CPU‑bound tasks, at the cost<br>    of higher overhead (process creation, IPC).<br>    &quot;&quot;&quot;<br>    processes = []<br><br>    # Create 5 processes, each running do_work with a different name.<br>    for i in range(5):<br>        p = multiprocessing.Process(target=do_work, args=(f&quot;process-{i}&quot;, 1))<br>        processes.append(p)<br><br>    # Start all processes: the OS can schedule them on multiple CPU cores.<br>    for p in processes:<br>        p.start()<br>    <br>    # Wait for all processes to complete.<br>    for p in processes:<br>        p.join()</pre><h4>With Coroutines</h4><p>In this case, the coroutines are driven by an application-level event loop that manages a queue of pending coroutines (driven one by one). All of them (and also the event loop) are executed in the same single thread.</p><p>You can run a coroutine in three different ways:</p><ul><li>asyncio.run(coro()) -&gt; called from regular function</li><li>asyncio.create_task(coro()) -&gt; called from a coroutine to schedule another coroutine to execute eventually</li><li>await coro() -&gt; transfer control to the coroutine object returned by coro()</li></ul><p>You can achieve concurrency by passing control from one coroutine to another.</p><pre>async def async_do_work(name, duration=1):  # ASYNC is all of nothing<br>    &quot;&quot;&quot;<br>    Asynchronous version of the work function.<br><br>    Instead of time.sleep (which blocks), we use asyncio.sleep,<br>    which *yields control* back to the event loop so other coroutines<br>    can run while this one is &quot;waiting&quot;.<br>    &quot;&quot;&quot;<br>    print(f&quot;[{name}] start&quot;)<br>    await asyncio.sleep(duration)  # non‑blocking sleep; cooperatively yields<br>    print(f&quot;[{name}] end&quot;)<br><br>async def run_with_coroutines():<br>    &quot;&quot;&quot;<br>    Run several copies of async_do_work concurrently using asyncio.<br><br>    All coroutines run in a *single* OS thread by default.<br>    Concurrency comes from cooperative yielding (await), not from threads.<br>    &quot;&quot;&quot;<br>    tasks = []<br><br>    # Create 5 coroutine objects for async_do_work.<br>    for i in range(5):<br>        coro = async_do_work(f&quot;coroutine-{i}&quot;, 1)<br>        tasks.append(coro)<br><br>    # Schedule them concurrently and wait for all to finish.<br>    # asyncio.gather runs them &quot;at the same time&quot; on the event loop.<br>    await asyncio.gather(*tasks)</pre><h4>Notes</h4><p>Usually, we use multiprocessing when we want to run CPU-intensive tasks because spawning a new process is costly. Threads and coroutines are almost equivalent in terms of performance. What it changes is the principle behind it:</p><ul><li>Coroutines yield control explicitly with the await keyword, while in the threads, you must start it, and then you are subjected to the interval suspension of the interpreter.</li><li>Threads (and processes) can be interrupted at any time by the OS scheduler, while with coroutines, code is protected against interruption by default.</li><li>With threads, you must remember to hold locks to protect the critical sections of the program; processes run isolated from each other; and async is executed in only one thread.</li></ul><h3>Why the GIL?</h3><p>If the GIL creates so many problems, why was Python designed like this in the first place? It was created to make CPython thread safe, making the (wrong) assumption that sequential code would have been enough. In 1991, CPUs were getting faster and faster, so they thought that a safer Python would have been better.</p><p>Unfortunately, this is no longer true, and the need of using concurrency is present more than ever. That’s why, since Python 3.13, the GIL has been made “optional”. Once the main libraries, such as NumPy and Pandas, support safe multi-threading, we might see a Python version without the GIL entirely.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6873e1231c84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coders-handbook/concurrency-parallelism-in-python-6873e1231c84">Concurrency &amp; Parallelism in Python</a> was originally published in <a href="https://medium.com/coders-handbook">Coder’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be Pythonic]]></title>
            <link>https://medium.com/coders-handbook/be-pythonic-7bd3a70ccbb5?source=rss----518a7aa0849---4</link>
            <guid isPermaLink="false">https://medium.com/p/7bd3a70ccbb5</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Stefano Lia]]></dc:creator>
            <pubDate>Mon, 04 May 2026 04:01:01 GMT</pubDate>
            <atom:updated>2026-05-04T04:01:01.318Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Python Framework for Coding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WfVWXnbkfCdzDuXYtp745g.jpeg" /><figcaption>Image Generated with AI</figcaption></figure><h3>Data Model</h3><p>Python data model is a framework that normalizes how we interact with its objects. We say an “object” is Pythonic when it develops some of the special methods in Python.</p><p>These methods are called “dunders”, which are all the functions that have two underscores at the beginning and at the end.</p><p>Python calls them automatically:</p><ul><li><em>__init</em>__ runs when you create an object</li><li><em>__bool__</em>runs when you call bool(obj)</li><li><em>__add__</em>runs when you do obj1 + obj2</li></ul><p>Using these methods, you’re teaching Python how your object should behave.</p><p>For example, if you want your object to have a string representation, you need to implement:</p><ul><li><strong>__repr__</strong>: provides a unique representation of the object. And this method is called whenever the function repr() is called over an object. It’s used in debugging, logs, and whenever you inspect an object in the terminal or Jupyter.</li><li><strong>__str__</strong>: provides a human-readable representation of the object. The goal of this method is to create something readable, while __repr__ provides a unique representation for debugging, which is different.</li></ul><blockquote>“If it walks like a duck and quacks like a duck, then it must be a duck” — Wikipedia.</blockquote><p>Instead, if you want your object to behave like a <strong>numeric type</strong>, you need to define the following methods:</p><ul><li>__repr__(self)</li><li>__abs__(self)</li><li>__add__(self, other)</li><li>__mul__(self, other)</li></ul><p>Duck typing is basically when you call a method and you “hope” it’s there. This is what makes Python fast and flexible, but it’s not the only way.</p><h4>Collections &amp; Goose Typing</h4><p>Duck typing fails at run-time; that’s why in Python we have the <strong>goose typing</strong>, which checks when an object belongs to any of the ABC classes available in the library collections.abc (such as Sequence, Mapping, or Set).</p><p>These classes explicitly define the types in Python:</p><ul><li>Sequence formalizes lists, strings, tuples</li><li>Mapping is implemented by dict and collections.defaultdict</li><li>Set is the interface of set and frozenset</li></ul><p>If you inherit from any ABC, you explicitly register the class to be that type.</p><p>You can also use these classes for type checking. Do you want to check if your object is a string?</p><pre>from collections.abc import Sequence<br>assert isinstance([1,2], Sequence)</pre><p>This ensures safety in your code.</p><h4>Sequences</h4><p>In Python, we have two main divisions for squences:</p><ul><li>Container (list, tuple, and collections.deque) vs Flat (str, bytes, array.array)</li><li>Mutable (list, bytearray, array.array, and collections.deque) vs Immutable (tuple, str, bytes)</li></ul><h4>Python Sequence Protocol</h4><p>To be a sequence in python, a class should implement:</p><ul><li>__len__(self): returns the length of the sequence</li><li>__getitem__(self, key): enables indexing and slicing</li></ul><p>Other optional methods for MutableSequence and optimization:</p><ul><li>__iter__(self): returns an iterator for the object</li><li>__contains__(self, item): checks for membership</li><li>__setitem__(self, key, value): updates an item at a specific, index obj[0] = val</li><li>__delitem__(self, key): deletes an item at an index, del obj[0]</li><li>__reversed__(self): returns an iterator in reverse order, reversed(obj)</li></ul><p>The list is the most common sequence in Python, but it’s not always the best option. If you want to store records or you know that the length of the sequence will never change, tuple is a better choice since it consumes less memory (8–20% savings for small data) and allows Python interpreter optimizations such as pre-allocation and faster iteration.</p><h4>Note on Lists Memory Usage</h4><p>Python, when we instantiate a list, keeps adjacent memory addresses, 8 bytes each, not raw data. This guarantees O(1) access in memory and manages the memory better.</p><p>When you compute a slice of a list, you create a new sub-list of references in memory. These addresses point to the same memory; therefore, we say the list copy is shallow.</p><p>Lists of memory references are not the optimal solution in memory because you need to save in RAM both addresses and the actual information; that’s why compact arrays (numpy and array.array when you choose the type a priori) — where the data is saved directly in the list — are a better solution.</p><p>Another problem with lists is that they have to be adjacent in order to be accessible in O(1). However, the list must have an end (and a size). Does this mean that every time we increase the list by one element, we need to copy this list somewhere else, adding that element? Well, Python optimizes it a little: when we create a list, the interpreter instantiates more memory so we can safely append elements in O(1); but yes, once we reach this limit, sometimes the whole list must be moved in memory to guarantee adjacent elements.</p><p>That’s why lists are not efficient in memory.</p><h4>List efficiency methods:</h4><ul><li>__setitem__(self, key, value): O(n) when the underlined array is resized; O(1) in a amortized sense</li><li>pop(): remove the last element of the list. O(n) when the array is shrunk; O(1) amortized</li><li>remove(value): Ω(n). There is no efficient way to remove an element based on its value. You find the element at index k, then you have to shift back all the elements until the end leftwards.</li><li>pop(k): O(n-k) -&gt; O(n). pop(0) -&gt; Ω(n)</li><li>append(value): O(1)</li><li>extend(list): O(n)</li></ul><h4>When NOT to use a List</h4><ul><li>If it contains only numbers or you need to handle millions of floating-point values, use array.array</li><li>When you make a view of a numeric array.array, use memoryview</li><li>You want parallel efficiency. Most of NumPy and SciPy functions are implemented in C or C++ and can use all the CPU cores because they release Python’s GIL.</li></ul><h3>Mutable vs Immutable Types</h3><p>This is one core difference in Python to remember.</p><h4>Immutable</h4><ul><li>Immutable types are objects you cannot alter once you create them.</li><li><strong>Core types</strong>: int, float, bool, str, tuple, and frozenset.</li><li>Every time you modify the object, you create a new instance of it.</li></ul><pre>x = &quot;hello&quot;<br>x += &quot;world&quot;  # -&gt; create a new string in memory<br></pre><h4>Mutable</h4><ul><li>Mutable types are objects that can be modified directly in memory.</li><li><strong>Core types</strong>: lists, dict, set, bytearray</li><li>Useful when you need to constantly update the object (the constant memory allocation would kill the performance)</li><li>Creates side-effects bugs</li></ul><p>Mutability and non-mutability allow you to do certain things in Python.</p><p>For example, memoryview can only be used if the underlying object is mutable.<br>Only numeric types and flat immutable types are hashable**. Container types are hashable if they are immutable and if all contained objects are hashable.</p><p>** In Python, an object is hashable if its hash code never changes during its lifetime. The hash is created using __hash__() dunder method. You must also implement __eq__() method so the element can be compared.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bd3a70ccbb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coders-handbook/be-pythonic-7bd3a70ccbb5">Be Pythonic</a> was originally published in <a href="https://medium.com/coders-handbook">Coder’s Handbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>