<?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 Sneha Jain on Medium]]></title>
        <description><![CDATA[Stories by Sneha Jain on Medium]]></description>
        <link>https://medium.com/@jainsnehasj6?source=rss-ba78657f0862------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Sneha Jain on Medium</title>
            <link>https://medium.com/@jainsnehasj6?source=rss-ba78657f0862------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:09:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jainsnehasj6/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[Mastering Relationships in MySQL: From Basics to Real Queries]]></title>
            <link>https://medium.com/@jainsnehasj6/mastering-relationships-in-mysql-from-basics-to-real-queries-312caee3f4d8?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/312caee3f4d8</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[relationships]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Mon, 04 May 2026 09:09:42 GMT</pubDate>
            <atom:updated>2026-05-04T09:09:42.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gv2v6nA0S1H_yHlp7d0LOQ.png" /></figure><p>When building real applications, data is never isolated. A user creates posts, a product belongs to a category, an order contains multiple items where everything is connected. These connections are called <strong>relationships in databases</strong>.</p><h3>What Are Relationships?</h3><p>A relationship defines how data in one table is connected to another.</p><p>Without relationships:</p><ul><li>Data is duplicated</li><li>Queries become messy</li></ul><p>With relationships:</p><ul><li>Data is structured</li><li>Queries become powerful</li></ul><h3>Types of Relationships in MySQL</h3><ul><li>One-to-One</li><li>One-to-Many</li><li>Many-to-One</li><li>Many-to-Many</li></ul><h4>1. One-to-One</h4><p>Each record in one table maps to exactly one record in another.</p><p><strong>Example</strong>: Each customer has one profile</p><pre>CREATE TABLE customers (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  name VARCHAR(100)<br>);<br><br>CREATE TABLE profiles (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  customer_id INT UNIQUE,<br>  address TEXT,<br>  FOREIGN KEY (customer_id) REFERENCES customers(id)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*arHObtDzHou-AL-LbU3ARQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*BknVbPGCTEl4vD9AR3cjQQ.png" /></figure><blockquote><strong>UNIQUE ensures one-to-one mapping</strong></blockquote><h4>2. One-to-Many</h4><p>One record can have multiple related records.</p><p><strong>Example</strong>: One customer → many orders</p><pre>CREATE TABLE orders (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  customer_id INT,<br>  FOREIGN KEY (customer_id) REFERENCES customers(id)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*u1cmAVobUZTfsmGJW0IUhw.png" /></figure><p><strong>The Rule: The foreign key goes on the “Many” side.</strong></p><h4>3. Many-to-One</h4><p>Multiple records point to a single record.</p><p><strong>Example</strong>: Many orders → one customer</p><blockquote><strong>One-to-many and many-to-one are the same relationship viewed from different sides.</strong></blockquote><h4>4. Many-to-Many</h4><p>Many records relate to many records.</p><p><strong>Example:</strong></p><ul><li>One order → many food items</li><li>One food item → many orders</li></ul><pre>CREATE TABLE food_items (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  name VARCHAR(100),<br>  price INT<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*GA1Pw0qNCTAz-d6Zlj1tog.png" /></figure><blockquote><strong>The Rule: The foreign key does not go in either of the original tables. You must create a third table (often called a junction or join table).</strong></blockquote><pre>CREATE TABLE order_items (<br>  order_id INT,<br>  food_id INT,<br>  quantity INT,<br>  FOREIGN KEY (order_id) REFERENCES orders(id),<br>  FOREIGN KEY (food_id) REFERENCES food_items(id)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*0FAdSCroaJACNMcTNTvkuw.png" /></figure><h3>Types of JOINs</h3><ol><li>INNER JOIN</li><li>LEFT JOIN</li><li>RIGHT JOIN</li><li>FULL OUTER JOIN</li></ol><h4>1. INNER JOIN</h4><p>Returns only matching records from both tables</p><p>Example: Get customers who have placed orders</p><pre>SELECT customers.name, orders.id AS order_id<br>FROM customers<br>JOIN orders ON customers.id = orders.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*xeuZxsoIRAdKIQaVHOJOow.png" /></figure><h4>2. LEFT JOIN</h4><p>Returns all records from the left table + matching from right</p><p>Example: Get all customers and their orders (including those with no orders)</p><pre>SELECT customers.name, orders.id AS order_id<br>FROM customers<br>LEFT JOIN orders <br>ON customers.id = orders.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*Q6yZvxkeAiO0TJiY8Vj2Fw.png" /></figure><h4>3. RIGHT JOIN</h4><p>Returns all records from the right table + matching from left</p><p><strong>Example</strong>: Get all orders and their customers</p><pre>SELECT customers.name, orders.id AS order_id<br>FROM customers<br>RIGHT JOIN orders <br>ON customers.id = orders.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*sInlGqvQmiUb7Gos8A29bQ.png" /></figure><h4>4. FULL OUTER JOIN</h4><ul><li>All matching records</li><li>Plus unmatched from both sides</li></ul><pre>SELECT customers.name, orders.id<br>FROM customers<br>LEFT JOIN orders ON customers.id = orders.customer_id<br><br>UNION<br><br>SELECT customers.name, orders.id<br>FROM customers<br>RIGHT JOIN orders ON customers.id = orders.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*GgeYycN_h6hkDwrJfoO6VQ.png" /></figure><h3>BONUS — Sample JOIN Queries</h3><ol><li>Total Orders per Customer</li></ol><pre>SELECT customers.name, COUNT(orders.id) AS total_orders<br>FROM customers<br>LEFT JOIN orders <br>ON customers.id = orders.customer_id<br>GROUP BY customers.name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*O9KW1zETp3sG-K5sUEybbg.png" /></figure><p>2. Find Customers with No Orders</p><pre>SELECT customers.name<br>FROM customers<br>LEFT JOIN orders <br>ON customers.id = orders.customer_id<br>WHERE orders.id IS NULL;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*0TKIqRO79BVlQdZl6CrDnQ.png" /></figure><p>3. Most Ordered Food Items</p><pre>SELECT food_items.name, SUM(order_items.quantity) AS total_ordered<br>FROM order_items<br>JOIN food_items <br>ON food_items.id = order_items.food_id<br>GROUP BY food_items.name<br>ORDER BY total_ordered DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*AuXIPy42rZYwa0Mf6JpGTg.png" /></figure><p>4. Get orders with food items and quantity</p><pre>SELECT orders.id, food_items.name, order_items.quantity<br>FROM order_items<br>JOIN orders ON orders.id = order_items.order_id<br>JOIN food_items ON food_items.id = order_items.food_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*jChupsj-jU9VbusR9wIT6Q.png" /></figure><h3>Bonus: Advanced Relationships &amp; JOINs</h3><h4>1. Self-Referencing Relationship</h4><p>A table can reference itself.</p><p><strong>Example</strong>:</p><ul><li>Employees and Managers</li><li>A manager is also an employee</li></ul><pre>CREATE TABLE employees (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  name VARCHAR(100),<br>  manager_id INT,<br>  FOREIGN KEY (manager_id) REFERENCES employees(id)<br>);</pre><p>Query: Get Employees with Their Managers</p><pre>SELECT e.name AS employee, m.name AS manager<br>FROM employees e<br>LEFT JOIN employees m <br>ON e.manager_id = m.id;</pre><h4>2. CROSS JOIN</h4><p>Returns all possible combinations of rows.</p><blockquote>Every row from table A × every row from table B</blockquote><pre>SELECT customers.name, food_items.name<br>FROM customers<br>CROSS JOIN food_items;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*8ZabcvKv8LDfUySpHgeLqw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=312caee3f4d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySQL to MongoDB: A Developer’s Translation Guide]]></title>
            <link>https://medium.com/@jainsnehasj6/mysql-to-mongodb-a-developers-translation-guide-67a08c20b36b?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/67a08c20b36b</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 06:17:48 GMT</pubDate>
            <atom:updated>2026-04-27T06:17:48.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QYyTBBoDx7Lke1fcd-Gbw.png" /></figure><p>If you’ve spent time with SQL, switching to MongoDB can feel less like learning a new tool and more like learning a new <em>way of thinking</em>. The syntax changes, sure, but the real shift is conceptual: tables → collections, rows → documents, joins → embedding.</p><p>This guide is a <strong>side-by-side translation</strong> of common operations in <strong>MySQL</strong> and <strong>MongoDB</strong>, so you can map what you already know to how MongoDB works.</p><h3>The Shift</h3><p>Before jumping into commands, here’s the difference in one sentence:</p><ul><li><strong>MySQL</strong> → structured, relational, schema-first</li><li><strong>MongoDB</strong> → flexible, document-based, schema-optional</li></ul><p>In MySQL, you design structure <em>before</em> inserting data.<br> In MongoDB, structure evolves <em>with</em> your data.</p><h3>Create Database</h3><p><strong>MySQL</strong></p><pre>CREATE DATABASE movies;<br>USE movies;</pre><p><strong>MongoDB</strong></p><pre>use movies</pre><blockquote>MongoDB creates the DB only when data is inserted.</blockquote><h3>Create Structure</h3><blockquote><strong>Tables (MySQL):</strong> Structured rows with a fixed schema in which every record follows the same columns and data types.</blockquote><blockquote><strong>Collections (MongoDB):</strong> Flexible groups of JSON-like documents where each record can have different fields and structure.</blockquote><p><strong>MySQL (Table)</strong></p><pre>CREATE TABLE content (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  title VARCHAR(255),<br>  rating FLOAT,<br>  views INT<br>);</pre><pre>SHOW TABLES;<br>DESCRIBE content;</pre><p><strong>MongoDB (Collection)</strong></p><pre>db.createCollection(&quot;content&quot;)</pre><pre>show collections</pre><h3>Insert Data</h3><p><strong>MySQL</strong></p><pre>INSERT INTO content (title, rating, views)<br>VALUES <br>(&#39;Stranger Things&#39;, 8.6, 50000),<br>(&#39;Dark&#39;, 8.7, 30000),<br>(&#39;Money Heist&#39;, 8.2, 70000),<br>(&#39;Friends&#39;, 8.8, 70000);</pre><p><strong>MongoDB</strong></p><pre>db.content.insertMany([<br>  { title: &quot;Stranger Things&quot;, rating: 8.6, views: 50000 },<br>  { title: &quot;Dark&quot;, rating: 8.7, views: 30000 },<br>  { title: &quot;Money Heist&quot;, rating: 8.2, views: 70000 },<br>  { title: &quot;Friends&quot;, rating: 8.8, views: 70000 },<br>])</pre><h3>Read Data</h3><p><strong>MySQL</strong></p><pre>SELECT * FROM content;</pre><p><strong>MongoDB</strong></p><pre>db.content.find()</pre><h3>Read Selective Data</h3><p><strong>MySQL</strong></p><blockquote>Select only specific columns (title, rating) to return just the needed data from the table.</blockquote><pre>SELECT title, rating FROM content;</pre><p><strong>MongoDB</strong></p><blockquote>Explicitly exclude <em>_id</em> since MongoDB includes it by default.</blockquote><pre>db.content.find({}, {_id: 0, title:1, rating:1})</pre><h3>Filter Data</h3><h4>a. Equality</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content WHERE title = &#39;Dark&#39;;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({ title: &quot;Dark&quot; })</pre><h4>b. Not Equal (!=)</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content WHERE rating != 8.8;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({ rating: { $ne: 8.8 } })</pre><h4>c. Greater Than / Less Than</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content WHERE rating &gt; 8;<br>SELECT * FROM content WHERE rating &lt; 9;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({ rating: { $gt: 8 } })<br>db.content.find({ rating: { $lt: 9 } })</pre><h4>d. Greater Than or Equal / Less Than or Equal</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content WHERE rating &gt;= 8;<br>SELECT * FROM content WHERE rating &lt;= 9;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({ rating: { $gte: 8 } })<br>db.content.find({ rating: { $lte: 9 } })</pre><h4>e. AND Condition</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE rating &gt;= 8 AND views &gt; 4000;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  rating: { $gte: 8 },<br>  views: { $gt: 4000 }<br>})</pre><h4>f. OR Condition</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE rating &gt;= 9 OR views &gt; 6000;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  $or: [<br>    { rating: { $gte: 9 } },<br>    { views: { $gt: 6000 } }<br>  ]<br>})</pre><h4>g. IN (Match Multiple Values)</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE title IN (&#39;Dark&#39;, &#39;Money Heist&#39;);</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  title: { $in: [&quot;Dark&quot;, &quot;Money Heist&quot;] }<br>})</pre><h4>h. NOT IN</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE title NOT IN (&#39;Dark&#39;);</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  title: { $nin: [&quot;Dark&quot;] }<br>})</pre><h4>i. BETWEEN</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE rating BETWEEN 8 AND 9;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  rating: { $gte: 8, $lte: 9 }<br>})</pre><h4>j. LIKE</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE title LIKE &#39;%Dark%&#39;;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  title: { $regex: &quot;Dark&quot;, $options: &quot;i&quot; }<br>})</pre><h4>k. Starts With</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE title LIKE &#39;Da%&#39;;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  title: { $regex: &quot;^Da&quot;, $options: &quot;i&quot; }<br>})</pre><h4>l. Ends With</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE title LIKE &#39;%rk&#39;;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  title: { $regex: &quot;rk$&quot;, $options: &quot;i&quot; }<br>})</pre><h4>m. IS NULL</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE rating IS NULL;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({ rating: null })</pre><h4>n. IS NOT NULL</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>WHERE rating IS NOT NULL;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({ rating: { $ne: null } })</pre><h3>Sort</h3><h4>a. Ascending</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>ORDER BY rating ASC;</pre><p><strong>MongoDB</strong></p><pre>db.content.find().sort({ rating: 1 })</pre><h4>b. Descending</h4><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>ORDER BY rating DESC;</pre><p><strong>MongoDB</strong></p><pre>db.content.find().sort({ rating: -1 })</pre><h3>Aggregation</h3><h4>a. Count Total Records</h4><p><strong>MySQL</strong></p><pre>SELECT COUNT(*) FROM content;</pre><p><strong>MongoDB</strong></p><pre>db.content.countDocuments()</pre><h4>b. Average Rating</h4><p><strong>MySQL</strong></p><pre>SELECT AVG(rating) FROM content;</pre><p><strong>MongoDB</strong></p><pre>db.content.aggregate([<br>  { $group: { _id: null, avgRating: { $avg: &quot;$rating&quot; } } }<br>])</pre><h4>c. Total Views</h4><p><strong>MySQL</strong></p><pre>SELECT SUM(views) FROM content;</pre><p><strong>MongoDB</strong></p><pre>db.content.aggregate([<br>  { $group: { _id: null, totalViews: { $sum: &quot;$views&quot; } } }<br>])</pre><h4>d. Group By Rating</h4><p><strong>MySQL</strong></p><pre>SELECT rating, COUNT(*) <br>FROM content<br>GROUP BY rating;</pre><p><strong>MongoDB</strong></p><pre>db.content.aggregate([<br>  {<br>    $group: {<br>      _id: &quot;$rating&quot;,<br>      count: { $sum: 1 }<br>    }<br>  }<br>])</pre><h4>e. Max Views</h4><p><strong>MySQL</strong></p><pre>SELECT MAX(views) FROM content;</pre><p><strong>MongoDB</strong></p><pre>db.content.aggregate([<br>  { $group: { _id: null, maxViews: { $max: &quot;$views&quot; } } }<br>])</pre><h4>f. Min Rating</h4><p><strong>MySQL</strong></p><pre>SELECT MIN(rating) FROM content;</pre><p><strong>MongoDB</strong></p><pre>db.content.aggregate([<br>  { $group: { _id: null, minRating: { $min: &quot;$rating&quot; } } }<br>])</pre><h4>g. Find Highly Watched Categories</h4><p><strong>MySQL</strong></p><pre>SELECT rating, SUM(views) as totalViews<br>FROM content<br>GROUP BY rating<br>HAVING totalViews &gt; 60000;</pre><p><strong>MongoDB</strong></p><pre>db.content.aggregate([<br>  {<br>    $group: {<br>      _id: &quot;$rating&quot;,<br>      totalViews: { $sum: &quot;$views&quot; }<br>    }<br>  },<br>  {<br>    $match: { totalViews: { $gt: 100000 } }<br>  }<br>])</pre><h3>Limit Results</h3><p><strong>MySQL</strong></p><pre>SELECT * FROM content<br>LIMIT 3;</pre><p><strong>MongoDB</strong></p><pre>db.content.find().limit(3)</pre><h3>Update Data</h3><h4>MySQL</h4><blockquote>Use SET</blockquote><pre>UPDATE content<br>SET views = views + 1<br>WHERE title = &#39;Dark&#39;;<br><br>SELECT * FROM content WHERE title = &#39;Dark&#39;;</pre><h4>MongoDB</h4><blockquote>Use $set or $inc</blockquote><pre>db.content.updateOne(<br>  { title: &quot;Dark&quot; },<br>  { $set: { views: 20000} }<br>)<br><br>db.content.find({ title: &quot;Dark&quot; })</pre><pre>db.content.updateOne(<br>  { title: &quot;Dark&quot; },<br>  { $inc: { views: 1 } }<br>)<br><br>db.content.find({ title: &quot;Dark&quot; })</pre><h3>Delete Data</h3><h4>MySQL</h4><pre>DELETE FROM content<br>WHERE title = &#39;Money Heist&#39;;</pre><h4>MongoDB</h4><pre>db.content.deleteOne({ title: &quot;Money Heist&quot; })</pre><h3>BONUS 1 — CHEATSHEET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcJjRVZHPT9P2SxxhAy_bg.png" /></figure><h3>BONUS 2 — SAMPLE QUESTIONS</h3><ol><li><strong>Find the top 2 most viewed content with rating ≥ 8</strong></li></ol><p><strong>MySQL</strong></p><pre>SELECT *<br>FROM content<br>WHERE rating &gt;= 8<br>ORDER BY views DESC<br>LIMIT 2;</pre><p><strong>MongoDB</strong></p><pre>db.content.find({<br>  rating: { $gte: 8 }<br>})<br>.sort({ views: -1 })<br>.limit(2)</pre><p><strong>2. Fetch content with rating &gt; 8 and views &gt; 50,000, sorted by highest views, returning only title and rating.</strong></p><p><strong>MySQL</strong></p><pre>SELECT title, rating<br>FROM content<br>WHERE rating &gt; 8 AND views &gt; 50000<br>ORDER BY views DESC;</pre><p><strong>MongoDB</strong></p><pre>db.content.find(<br>  { rating: { $gt: 8 }, views: { $gt: 50000 } },<br>  { _id: 0, title: 1, rating: 1 }<br>).sort({ views: -1 })</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67a08c20b36b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NetworkX for Python — A Practical Guide to Datasets, Graph Storage and CSVs]]></title>
            <link>https://medium.com/@jainsnehasj6/networkx-for-python-a-practical-guide-to-datasets-graph-storage-and-csvs-6d42bace9d32?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d42bace9d32</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[networkx]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 15:37:53 GMT</pubDate>
            <atom:updated>2026-02-27T15:37:53.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*4z0JdyB5hl6PxRci8nIkWA.png" /></figure><p>In this part of the NetworkX series, we explore how to work with <strong>in-built datasets and custom CSV data</strong> using NetworkX. You’ll learn how to load real-world and benchmark networks, understand their structure, enrich graphs with node and edge attributes, and persist graphs using common file formats.</p><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installation</h3><pre>pip install networkx</pre><h3>Imports</h3><pre>import networkx as nx<br>import matplotlib.pyplot as plt</pre><h3>1. Built-in datasets</h3><p>NetworkX provides <strong>real-world in-built datasets</strong>. They come <strong>preloaded</strong>, so you can start analyzing immediately.</p><h4>a. Zachary’s Karate Club Graph</h4><p>The <strong>Karate Club Graph</strong> represents a friendship network of <strong>34 members</strong> of a university karate club.</p><ul><li>Classic dataset in network science</li><li>Used heavily for <strong>community detection</strong></li></ul><pre>G = nx.karate_club_graph()<br><br>print(&quot;Number of nodes:&quot;, G.number_of_nodes())<br>print(&quot;Number of edges:&quot;, G.number_of_edges())<br><br>pos = nx.spring_layout(G, seed=42)<br><br>nx.draw(G, pos, with_labels=True, node_color=&quot;lightblue&quot;, node_size=600, edge_color=&quot;gray&quot;)<br><br>plt.title(&quot;Zachary&#39;s Karate Club Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*5F4bz1pdM2vlaPKf1iJISQ.png" /><figcaption>Number of nodes &amp; edges</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*46hQW4Rd44hkjYEcpy8j4A.png" /><figcaption>Zachary’s Karate Club Graph</figcaption></figure><h4>b. Florentine Families Graph</h4><p>This dataset represents <strong>marriage relationships</strong> among influential families in Renaissance Florence.</p><ul><li>Demonstrates <strong>power and influence</strong></li><li>Great for <strong>centrality analysis</strong></li><li>Frequently used in sociology</li></ul><pre>G = nx.florentine_families_graph()<br><br>print(G.nodes())<br>print(G.edges())<br><br>nx.draw(G, with_labels=True, node_color=&quot;lightgreen&quot;, node_size=800)<br><br>plt.title(&quot;Florentine Families Network&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_RbsL8WRlvvAUOj7RFiXg.png" /><figcaption>Nodes and Edges</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*cwMkperBQ9d3-pqckEmJ8g.png" /><figcaption>Florentine Families Graph</figcaption></figure><h4>c. Davis Southern Women Graph</h4><p>This dataset models <strong>women attending social events</strong>, forming a <strong>bipartite graph</strong>.</p><ul><li>Shows <strong>bipartite graph structure</strong></li><li>Useful for projections</li><li>Common in social network analysis</li></ul><pre>G = nx.davis_southern_women_graph()<br><br>print(&quot;Number of nodes:&quot;, G.number_of_nodes())<br>print(&quot;Number of edges:&quot;, G.number_of_edges())<br><br>women = {n for n, d in G.nodes(data=True) if d[&quot;bipartite&quot;] == 0}<br>events = set(G) - women<br><br>pos = {}<br>pos.update((n, (0, i)) for i, n in enumerate(women))<br>pos.update((n, (1, i)) for i, n in enumerate(events))<br><br>plt.figure(figsize=(12, 8))<br><br>nx.draw(G, pos, with_labels=True, node_size=800,<br>    node_color=[&quot;lightpink&quot; if n in women else &quot;lightblue&quot; for n in G],<br>    edge_color=&quot;gray&quot;<br>)<br><br>plt.title(&quot;Davis Southern Women Bipartite Graph&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><p>The <strong>Davis Southern Women</strong> dataset has <strong>two different types of nodes</strong>:</p><ul><li><strong>Women</strong> → names like <em>Evelyn Jefferson, Laura Mandeville</em></li><li><strong>Events</strong> → nodes like <em>E1, E2, E3…</em></li></ul><p>Edges mean: A woman attended an event</p><p>So, we split nodes into two sets and position nodes in two vertical columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*zorFv7KSt0wmTmGcFSb3-g.png" /><figcaption>Number of nodes and edges</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCy4vLDiYCjmKgKxFVpmIw.png" /><figcaption>Davis Southern Women Graph</figcaption></figure><h4>d. Les Misérables Character Network</h4><p>This dataset represents <strong>co-occurrence of characters</strong> in <em>Les Misérables</em>.</p><ul><li>Weighted edges</li><li>Natural community structure</li><li>Perfect for centrality &amp; clustering</li></ul><pre>G = nx.les_miserables_graph()<br><br>print(&quot;Nodes:&quot;, G.number_of_nodes())<br>print(&quot;Edges:&quot;, G.number_of_edges())<br><br>pos = nx.spring_layout(G, seed=42)<br><br>nx.draw(G, pos, with_labels=True, node_size=400, node_color=&quot;orange&quot;)<br><br>plt.title(&quot;Les Misérables Character Network&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*lcUspTQyI79hNaXr-wSI3A.png" /><figcaption>Number of Nodes and Edges</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdpJ7KB0hIwpkM121MiQSA.png" /><figcaption>Les Misérables Character Network</figcaption></figure><p>Les Misérables dataset is dense and highly connected. Visualizing all nodes and labels at once results in clutter.</p><h4>e. Krackhardt Kite Graph</h4><p>A small but powerful dataset designed to highlight <strong>differences between centrality measures</strong>.</p><ul><li>Same number of connections ≠ same importance</li><li>Ideal for teaching centrality concepts</li></ul><pre>G = nx.krackhardt_kite_graph()<br><br>print(&quot;Nodes:&quot;, G.number_of_nodes())<br>print(&quot;Edges:&quot;, G.number_of_edges())<br><br>pos = nx.spring_layout(G, seed=42)<br><br>nx.draw(G, pos, with_labels=True, node_size=400, node_color=&quot;pink&quot;)<br><br>plt.title(&quot;Krackhardt Kite Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*3MSGysbcKEpZd2IYeCDkGA.png" /><figcaption>Number of Nodes and Edges</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1v_IB4LgXZqkbGnuPSI4Rg.png" /><figcaption>Krackhardt Kite Graph</figcaption></figure><h3>2. Reading and Writing Graphs in NetworkX</h3><p>Once a graph is created or loaded, it’s often useful to <strong>save it</strong>, <strong>share it</strong>, or <strong>reload it later</strong>.</p><pre>import networkx as nx<br><br>G = nx.Graph()<br>G.add_edge(1, 2, weight=4.5)<br>G.add_edge(2, 3, weight=2.0)</pre><h4>1. GraphML</h4><p>One of the most popular formats because it supports:</p><ul><li>Node attributes</li><li>Edge attributes</li><li>Directed and undirected graphs</li></ul><p><strong>Write Graph to File</strong></p><pre>nx.write_graphml(G, &quot;graph.graphml&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owA2gtTa51szH_TMKHmTYQ.png" /><figcaption>graph.graphml</figcaption></figure><p><strong>Read Graph from File</strong></p><pre>G2 = nx.read_graphml(&quot;graph.graphml&quot;)<br><br>print(&quot;Nodes in G2:&quot;, G2.nodes(data=True))<br>print(&quot;Edges in G2:&quot;, G2.edges(data=True))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*uJrGzsb1wdN0czH0y9vwgA.png" /><figcaption>Read Graph from File</figcaption></figure><h4>2. GEXF</h4><p><strong>GEXF </strong>works well with <strong>Gephi</strong> or other visualization tools.</p><p><strong>Write Graph to File</strong></p><pre>nx.write_gexf(G, &quot;graph.gexf&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPDZgvqxPB5Oas5J3QkEtQ.png" /><figcaption>graph.gexf</figcaption></figure><p><strong>Read Graph from File</strong></p><pre>G2 = nx.read_gexf(&quot;graph.gexf&quot;)<br><br>print(&quot;Nodes in G2:&quot;, G2.nodes(data=True))<br>print(&quot;Edges in G2:&quot;, G2.edges(data=True))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*S-NOOOGtnWLNoTgh_LsKTQ.png" /><figcaption>Read Graph from File</figcaption></figure><h4>3. Edge List Format</h4><p>Stores graphs as plain text edge lists. Best for: Simple graphs, Large datasets, Quick sharing</p><p><strong>Write Graph to File</strong></p><pre>nx.write_edgelist(G, &quot;graph.edgelist&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*_hEU_yq3OrJnZnrObUr_Ew.png" /><figcaption>graph.edgelist</figcaption></figure><p><strong>Read Graph from File</strong></p><pre>G2 = nx.read_edgelist(&quot;graph.edgelist&quot;)<br><br>print(&quot;Nodes in G2:&quot;, G2.nodes(data=True))<br>print(&quot;Edges in G2:&quot;, G2.edges(data=True))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*WaU8qvcil3APzuplHCce0w.png" /><figcaption>Read Graph from File</figcaption></figure><h4>4. Adjacency List Format</h4><p>Stores neighbors of each node. Best for: Sparse graphs, Compact storage</p><p><strong>Write Graph to File</strong></p><pre>nx.write_adjlist(G, &quot;graph.adjlist&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*YR2agpmZzFqfsFgIugxGvg.png" /><figcaption>graph.adjlist</figcaption></figure><p><strong>Read Graph from File</strong></p><pre>G2 = nx.read_adjlist(&quot;graph.adjlist&quot;)<br><br>print(&quot;Nodes in G2:&quot;, G2.nodes(data=True))<br>print(&quot;Edges in G2:&quot;, G2.edges(data=True))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*j2cuBfZkHpmoxqrIuabJfA.png" /><figcaption>Read Graph from File</figcaption></figure><h4>5. Pickle Format</h4><p>Stores the entire graph object exactly as-is.</p><ul><li>Fast save/load</li><li>Internal Python workflows</li></ul><p><strong>Write Graph to File</strong></p><pre>import pickle<br><br>with open(&quot;graph.pkl&quot;, &quot;wb&quot;) as f:<br>    pickle.dump(G, f)</pre><p><strong>Read Graph from File</strong></p><pre>import pickle<br><br>with open(&quot;graph.pkl&quot;, &quot;rb&quot;) as f:<br>    G_loaded = pickle.load(f)<br>    <br>print(&quot;Nodes: &quot;, list(G_loaded.nodes(data=True)))<br>print(&quot;Edges: &quot;, list(G_loaded.edges(data=True)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*rrO5V_gpkXzpxOUeKqwo4Q.png" /><figcaption>Read Graph from File</figcaption></figure><h3>BONUS — Using Custom CSV Datasets in NetworkX</h3><p>While NetworkX provides useful in-built datasets, real-world graph analysis often starts with <strong>custom data stored in CSV files</strong>. NetworkX makes it easy to convert CSV data into graphs with minimal code.</p><h4>Common CSV Formats for Graphs</h4><p><strong>1. Edge List (edges.csv)</strong></p><pre>source,target<br>A,B<br>B,C<br>C,D<br>A,D</pre><p><strong>2. Weighted Edge List (</strong><strong>weighted_edges.csv)</strong></p><pre>source,target,weight<br>A,B,4<br>B,C,2<br>C,D,3<br>A,D,5</pre><h4>1. Creating an Undirected Graph from Edge List</h4><pre>import pandas as pd<br>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>df = pd.read_csv(&quot;edges.csv&quot;)<br>G = nx.from_pandas_edgelist(df, &quot;source&quot;, &quot;target&quot;)<br><br>nx.draw(G, with_labels=True, node_color=&quot;lightblue&quot;, node_size=800)<br>plt.title(&quot;Undirected Graph from CSV&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*f3Nm0xpbEUj6Otd8D-zLFA.png" /><figcaption>Creating an Undirected Graph from Edge List</figcaption></figure><h4>2. Creating a Directed Graph from Edge List</h4><pre>import pandas as pd<br>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>df = pd.read_csv(&quot;edges.csv&quot;)<br>DG = nx.from_pandas_edgelist(df, &quot;source&quot;, &quot;target&quot;, create_using=nx.DiGraph())<br><br>nx.draw(DG, with_labels=True, node_color=&quot;lightgreen&quot;, node_size=800, arrows=True)<br>plt.title(&quot;Directed Graph from CSV&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*X70KLpjA9PFNMYm-3xJGEg.png" /><figcaption>Creating a Directed Graph from Edge List</figcaption></figure><h4>3. Creating a Weighted Graph from Weighted Edge List</h4><pre>import pandas as pd<br>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>df = pd.read_csv(&quot;weighted_edges.csv&quot;)<br><br>WG = nx.from_pandas_edgelist(df, &quot;source&quot;, &quot;target&quot;, edge_attr=&quot;weight&quot;)<br><br>pos = nx.spring_layout(WG, seed=42)<br><br>nx.draw(WG, pos, with_labels=True, node_color=&quot;lightcoral&quot;, node_size=800)<br>nx.draw_networkx_edge_labels(WG, pos, edge_labels=nx.get_edge_attributes(WG, &quot;weight&quot;))<br><br>plt.title(&quot;Weighted Graph from CSV&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*EelkwFA25AevcYHsg3NF4Q.png" /></figure><h4>4. Graph with Node Attributes</h4><p><strong>Node CSV (</strong><strong>nodes.csv)</strong></p><pre>node,role<br>A,Admin<br>B,User<br>C,User<br>D,Guest</pre><pre>import pandas as pd<br>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>edges = pd.read_csv(&quot;edges.csv&quot;)<br>nodes = pd.read_csv(&quot;nodes.csv&quot;)<br><br>G = nx.from_pandas_edgelist(edges, &quot;source&quot;, &quot;target&quot;)<br><br>for _, row in nodes.iterrows():<br>    G.nodes[row[&quot;node&quot;]][&quot;role&quot;] = row[&quot;role&quot;]<br><br>color_map = {<br>    &quot;Admin&quot;: &quot;gold&quot;,<br>    &quot;User&quot;: &quot;skyblue&quot;,<br>    &quot;Guest&quot;: &quot;lightgray&quot;<br>}<br><br>node_colors = [color_map[G.nodes[n][&quot;role&quot;]] for n in G.nodes()]<br><br>nx.draw(G, with_labels=True, node_color=node_colors, node_size=800)<br><br>plt.title(&quot;Graph with Node Attributes&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yS4WPM-Gs47oDzB7i0H0Zw.png" /><figcaption>Graph with Node Attributes</figcaption></figure><h3>Conclusion</h3><p>In this guide, you explored how NetworkX makes it easy to work with <strong>datasets and external data sources</strong>, from built-in benchmark networks to custom CSV-based graphs. If you haven’t read the earlier parts of this series, I recommend starting with them.</p><p>Stay tuned for the next installment, where we’ll dive into <strong>centrality measures and community detection</strong> to uncover influence and structure within real-world networks using NetworkX.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d42bace9d32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NetworkX for Python — A Practical Guide to Graph Generators]]></title>
            <link>https://medium.com/@jainsnehasj6/networkx-for-python-a-practical-guide-to-graph-generators-1932664f545e?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/1932664f545e</guid>
            <category><![CDATA[networkx]]></category>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 10:10:51 GMT</pubDate>
            <atom:updated>2026-02-10T10:10:51.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*G9wtIb382hy_7jnWlVNNeg.png" /></figure><p>Real-world networks are often <strong>large, random, or follow specific patterns</strong>.<br>NetworkX provides <strong>graph generators</strong> that help you <strong>simulate, test, and study</strong> such networks without manually creating nodes and edges.</p><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installation</h3><pre>pip install networkx</pre><h3>Imports</h3><pre>import networkx as nx<br>import matplotlib.pyplot as plt</pre><h3>a. Erdős–Rényi Model (Random Graphs):</h3><p>Edges are created <strong>randomly</strong> between nodes with probability p.</p><ul><li>n → number of nodes</li><li>p → probability that an edge exists</li><li>No hubs or structure</li><li>Low clustering</li><li>Degree distribution ≈ binomial (or Poisson)</li></ul><pre>G = nx.erdos_renyi_graph(n=10, p=0.3)<br><br>nx.draw(G, with_labels=True, node_color=&quot;lightblue&quot;, node_size=800)<br>plt.title(&quot;Erdős–Rényi Random Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*GxdUadpKy10jgcBgwMOD4Q.png" /><figcaption>Erdős–Rényi Model (Random Graphs)</figcaption></figure><p><strong>Use case: </strong>Random networks &amp; Baseline comparisons</p><h3>b. Barabási–Albert Graph (Scale-Free Networks):</h3><p>New nodes prefer to connect to <strong>already well-connected nodes </strong>(<em>preferential attachment</em>).</p><ul><li>n → number of nodes</li><li>m → edges added per new node</li><li>Strong hubs</li><li>Power-law degree distribution</li><li>Robust to random failures</li></ul><pre>G = nx.barabasi_albert_graph(n=15, m=2)<br><br>nx.draw(G, with_labels=True, node_color=&quot;orange&quot;, node_size=800)<br>plt.title(&quot;Barabási–Albert Scale-Free Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2IH5UfvG998OgDdroXivgQ.png" /><figcaption>Barabási–Albert Graph (Scale-Free Networks)</figcaption></figure><p><strong>Use Case: </strong>Social networks &amp; Web links</p><h3>c. Watts–Strogatz Graph (Small-World Networks):</h3><p>Start with a regular lattice, then randomly rewire edges.</p><ul><li>k → neighbors per node</li><li>p → rewiring probability</li><li>Combines randomness and structure</li><li>High clustering</li><li>Short average path length</li></ul><pre>G = nx.watts_strogatz_graph(n=12, k=4, p=0.3)<br><br>nx.draw(G, with_labels=True, node_color=&quot;lightgreen&quot;, node_size=800)<br>plt.title(&quot;Watts–Strogatz Small-World Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*t_v4rAcOFaS-pENVK_U9hQ.png" /><figcaption>Watts–Strogatz Graph (Small-World Networks)</figcaption></figure><p><strong>Use case: </strong>Social &amp; Brain networks</p><h3>e. Random Regular Graph</h3><p>Every node has the same degree.</p><pre>G = nx.random_regular_graph(d=3, n=10)<br><br>nx.draw(G, with_labels=True, node_color=&#39;lightpink&#39;, node_size=800)<br>plt.title(&quot;Random Regular Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*kYHHUdVdf8-IyJqEBf0TMg.png" /><figcaption>Random Regular Graph</figcaption></figure><h3>f. Random Directed Graph</h3><pre>G = nx.gnp_random_graph(5, 0.3, directed=True)<br><br>nx.draw(G, with_labels=True, node_color=&#39;lightgreen&#39;, node_size=800)<br>plt.title(&quot;Random Regular Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1WuPKZfAj4RlVULNeXpdEg.png" /><figcaption>Random Directed Graph</figcaption></figure><p><strong>Use Case: </strong>Directed relationship modelling &amp; Algorithm stress testing</p><h3>g. Tournament Graph</h3><p>Every pair has exactly one directed edge.</p><pre>G = nx.tournament.random_tournament(8)<br><br>nx.draw(G, with_labels=True, node_color=&#39;orange&#39;, node_size=800)<br>plt.title(&quot;Tournament Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*EDbBBfYb2M14QPLZyC6hDg.png" /><figcaption>Tournament Graph</figcaption></figure><p><strong>Use Case: </strong>Pairwise ranking &amp; Preference modelling</p><h3>h. Complete Bipartite Graph</h3><pre>G = nx.complete_bipartite_graph(4, 3)<br><br>nx.draw(G, with_labels=True, node_color=&#39;brown&#39;, node_size=800)<br>plt.title(&quot;Complete Bipartite Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5srimljNKYiWxZ2Q7alZNQ.png" /><figcaption>Complete Bipartite Graph</figcaption></figure><p><strong>Use Case: </strong>Two-group modeling &amp; maximum matching</p><h3>i. Random Bipartite Graph</h3><pre>G = nx.bipartite.random_graph(5, 4, p=0.4)<br><br>nx.draw(G, with_labels=True, node_color=&#39;olive&#39;, node_size=800)<br>plt.title(&quot;Random Complete Bipartite Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*-uMS-J7PGmhWhm0G4GUSTw.png" /><figcaption>Random Bipartite Graph</figcaption></figure><p><strong>Use Case: </strong>Uncertain relationship modeling &amp; bipartite baselines</p><h3>j. Grid Graph</h3><p>Nodes arranged in a grid structure.</p><pre>G = nx.grid_2d_graph(4, 4)<br><br>nx.draw(G, with_labels=True, node_size=600)<br>plt.title(&quot;2D Grid Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_Y-JIVQqaW3uJHkm19RCRg.png" /><figcaption>Grid Graph</figcaption></figure><p><strong>Use Case: </strong>Maps &amp; Game boards</p><h3>k. Hexagonal Lattice</h3><pre>G = nx.hexagonal_lattice_graph(3, 3)<br><br>nx.draw(G, with_labels=True, node_color=&#39;pink&#39;, node_size=800)<br>plt.title(&quot;Hexagonal Lattice Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ljHUb_FhSoBOMnqeN6up2w.png" /><figcaption>Hexagonal Lattice</figcaption></figure><h3>l. Triangular Lattice</h3><pre>G = nx.triangular_lattice_graph(4, 4)<br><br>nx.draw(G, with_labels=True, node_color=&#39;cyan&#39;, node_size=800)<br>plt.title(&quot;Triangular Lattice Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*U7QzEf5zV9Rz1bIcexjS2Q.png" /><figcaption>Triangular Lattice</figcaption></figure><h3>m. Balanced Tree</h3><p>Binary tree when r=2.</p><pre>G = nx.balanced_tree(r=2, h=3)<br><br>nx.draw(G, with_labels=True, node_color=&#39;gold&#39;, node_size=800)<br>plt.title(&quot;Balanced Tree Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*MEVjpr_rzOlTFMxyYkbWVA.png" /><figcaption>Balanced Tree</figcaption></figure><h3>n. Prefix Tree (Trie)</h3><pre>G = nx.prefix_tree([&quot;cat&quot;, &quot;car&quot;, &quot;dog&quot;])<br><br>labels = {n: d.get(&quot;source&quot;, &quot;ROOT&quot;) for n, d in G.nodes(data=True)}<br><br>def hierarchy_pos(G, root=0, width=1., vert_gap=0.2, vert_loc=0, xcenter=0.5):<br>    pos = {root:(xcenter, vert_loc)}<br>    children = list(G.successors(root))<br>    if children:<br>        dx = width / len(children)<br>        x = xcenter - width/2 + dx/2<br>        for child in children:<br>            pos.update(<br>                hierarchy_pos(<br>                    G, child, width=dx,<br>                    vert_gap=vert_gap,<br>                    vert_loc=vert_loc-vert_gap,<br>                    xcenter=x<br>                )<br>            )<br>            x += dx<br>    return pos<br><br>pos = hierarchy_pos(G)<br><br>plt.figure(figsize=(8,6))<br><br>nx.draw_networkx_nodes(G, pos, node_color=&quot;skyblue&quot;, node_size=900)<br>nx.draw_networkx_edges(G, pos, arrows=True, arrowstyle=&quot;-|&gt;&quot;, arrowsize=25)<br>nx.draw_networkx_labels(G, pos, labels)<br><br>plt.title(&quot;Prefix Tree (Trie)&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tZWKUQLSYdqRnMqnwLIRPw.png" /><figcaption>Prefix Tree (Trie)</figcaption></figure><p><strong>Use Case: </strong>Used in string processing and NLP.</p><h3>o. Configuration Model</h3><p>Generates a graph from a given degree sequence.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>deg_seq = [3,3,2,2,2,1,1]<br>G = nx.configuration_model(deg_seq)<br><br>nx.draw(G, with_labels=True, node_color=&#39;crimson&#39;, node_size=800)<br>plt.title(&quot;Configuration Model Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1lfQji2DnaOuF_MlhMBcGA.png" /><figcaption>Configuration Model</figcaption></figure><p><strong>Use case: </strong>Model real networks with known degree distributions.</p><h3>BONUS — Classic and Famous Graphs</h3><h4>a. Complete Graph (Kₙ)</h4><p>Every node is connected to every other node.</p><ul><li>Maximum density</li><li>Diameter = 1</li><li>Worst-case complexity</li></ul><pre>G = nx.complete_graph(10)<br><br>nx.draw(G, with_labels=True, node_color=&quot;pink&quot;, node_size=800)<br>plt.title(&quot;Complete Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*7jgtDZdAwcY0Ck_FPXBAHQ.png" /><figcaption>Complete Graph</figcaption></figure><h4>b. Path Graph (Pₙ)</h4><p>Nodes connected in a straight line.</p><ul><li>Linear workflows</li><li>Chain-like dependencies</li></ul><pre>G = nx.path_graph(10)<br><br>nx.draw(G, with_labels=True, node_color=&quot;lightgray&quot;, node_size=800)<br>plt.title(&quot;Path Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KtSP_GmU2MW1-UYGvkqpaA.png" /><figcaption>Path Graph</figcaption></figure><h4>c. Cycle Graph (Cₙ)</h4><p>Nodes form a single closed loop.</p><ul><li>Circular dependencies</li><li>Ring networks</li><li>Each node has degree 2</li></ul><pre>G = nx.cycle_graph(10)<br><br>nx.draw(G, with_labels=True, node_color=&quot;violet&quot;, node_size=800)<br><br>plt.title(&quot;Cycle Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*lL6B0odjEJVC9AauPCCyQw.png" /><figcaption>Cycle Graph</figcaption></figure><h4>d. Star Graph (Sₙ)</h4><p>One central node connected to all others.</p><ul><li>Hub-and-spoke models</li><li>Centralized systems</li></ul><pre>G = nx.star_graph(10)<br><br>nx.draw(G, with_labels=True, node_color=&quot;gold&quot;, node_size=800)<br>plt.title(&quot;Star Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*CvHjTEiBt52nqVmLO2C6dg.png" /><figcaption>Star Graph</figcaption></figure><h4>f. Petersen Graph</h4><ul><li>10 nodes, 15 edges</li><li>3-regular (each node has degree 3)</li><li>Non-planar</li></ul><pre>G = nx.petersen_graph()<br><br>nx.draw(G, with_labels=True, node_color=&quot;brown&quot;, node_size=800)<br>plt.title(&quot;Petersen Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1SWG1QVbDy1qenb78QGkNg.png" /><figcaption>Petersen Graph</figcaption></figure><h4>g. Tetrahedral Graph</h4><ul><li>Complete graph K₄</li><li>Fully connected 3D tetrahedron</li><li>Planar</li></ul><pre>G = nx.tetrahedral_graph()<br><br>nx.draw(G, with_labels=True, node_color=&quot;cyan&quot;, node_size=800)<br>plt.title(&quot;Tetrahedral Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*nhvdPLmpAQtwkstAX9HTpw.png" /><figcaption>Tetrahedral Graph</figcaption></figure><h4>h. Wheel Graph (Wₙ)</h4><p>A cycle graph with a central hub.</p><ul><li>Combination of star + cycle</li><li>Often planar</li></ul><pre>G = nx.wheel_graph(6)<br><br>nx.draw(G, with_labels=True, node_color=&quot;olive&quot;, node_size=800)<br><br>plt.title(&quot;Wheel Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*P1FVDiI8ELBwhKxpfWe8hg.png" /><figcaption>Wheel Graph</figcaption></figure><h4>g. Ladder Graph</h4><p>Looks like a ladder.</p><ul><li>Cartesian product of Pₙ × P₂</li><li>Used in routing and grid explanations</li></ul><pre>G = nx.ladder_graph(10)<br><br>nx.draw(G, with_labels=True, node_color=&#39;lightblue&#39;, node_size=800)<br><br>plt.title(&quot;Ladder Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZKamEZahe7-HQqYoD-3SrA.png" /><figcaption>Ladder Graph</figcaption></figure><h4>h. Barbell Graph</h4><p>Two complete graphs connected by a path.</p><ul><li>Useful for connectivity and robustness analysis</li></ul><pre>G = nx.barbell_graph(4, 2)<br><br>nx.draw(G, with_labels=True, node_color=&#39;orange&#39;, node_size=800)<br>plt.title(&quot;Barbell Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hSIxyn8mV5I9ZKhZzmCEZw.png" /><figcaption>Barbell Graph</figcaption></figure><h4>i. Lollipop Graph</h4><p>Complete graph connected to a path.</p><ul><li>Famous for worst-case random walk behaviour</li></ul><pre>G = nx.lollipop_graph(4, 3)<br><br>nx.draw(G, with_labels=True, node_color=&#39;pink&#39;, node_size=800)<br>plt.title(&quot;Lollipop Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OMoLA0ZgqxtrrfAtEh7UQg.png" /><figcaption>Lollipop Graph</figcaption></figure><h4>j. Cube Graph</h4><pre>G = nx.cubical_graph()<br><br>nx.draw(G, with_labels=True, node_color=&#39;violet&#39;, node_size=800)<br>plt.title(&quot;Cubical Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qW8YqsWwY_e8wQV8zrxHkw.png" /><figcaption>Cube Graph</figcaption></figure><h4>k. Octahedral Graph</h4><pre>G = nx.octahedral_graph()<br><br>nx.draw(G, with_labels=True, node_color=&#39;purple&#39;, node_size=800)<br>plt.title(&quot;Octahedral Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*D2OBM3GB856WwTF6bVuBYg.png" /><figcaption>Octahedral Graph</figcaption></figure><h4>l. Icosahedral Graph</h4><ul><li>12 nodes</li><li>Symmetric</li></ul><pre>G = nx.icosahedral_graph()<br><br>nx.draw(G, with_labels=True, node_color=&#39;lightgreen&#39;, node_size=800)<br>plt.title(&quot;Icosahedral Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5gmmidKGU9FbdThXTZVYOA.png" /><figcaption>Icosahedral Graph</figcaption></figure><h4>i. Dodecahedral Graph</h4><ul><li>20 nodes</li><li>Highly symmetric</li></ul><pre>G = nx.dodecahedral_graph()<br><br>nx.draw(G, with_labels=True, node_color=&#39;lightpink&#39;, node_size=800)<br>plt.title(&quot;Dodecahedral Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*aHZ5a915fd_xI7e0TH4_kg.png" /><figcaption>Dodecahedral Graph</figcaption></figure><h3>Conclusion</h3><p>In this guide, you explored how <strong>NetworkX graph generators</strong> make it easy to create a wide variety of network structures. If you haven’t read the earlier parts of this series, I recommend starting with the earlier blogs.</p><p>Stay tuned for the next part, where we’ll explore <strong>in-built datasets and real-world network analysis using NetworkX</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1932664f545e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NetworkX for Python — A Practical Guide to Cycle Detection and Connectivity Algorithms]]></title>
            <link>https://medium.com/@jainsnehasj6/networkx-for-python-a-practical-guide-to-cycle-detection-and-connectivity-algorithms-f6025c73915d?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6025c73915d</guid>
            <category><![CDATA[networkx]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[python-libraries]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 06:37:08 GMT</pubDate>
            <atom:updated>2026-01-16T06:37:08.912Z</atom:updated>
            <content:encoded><![CDATA[<h3>NetworkX for Python — A Practical Guide to Cycle Detection and Connectivity Algorithms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLi_CYPBPaDZwMVgc6WF7Q.png" /></figure><p>In this part of the NetworkX series, we explore how to detect cycles, identify connected components, check strong and weak connectivity, find bridges and articulation points, and visualize graphs with clear, intuitive plots.</p><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installation</h3><pre>pip install networkx</pre><h3>1. Cycle Detection in Graphs</h3><p>Cycles are paths where you can start at a node and return to it without repeating edges.</p><ul><li><strong>Undirected graphs:</strong> A cycle exists if there’s a loop of length ≥ 3.</li><li><strong>Directed graphs:</strong> A cycle exists if following edges leads back to the same node.</li></ul><h4>a. Undirected Graph Cycles (cycle_basis)</h4><p>nx.cycle_basis(G) finds <strong>all independent cycles</strong> in an undirected graph.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>G = nx.Graph()<br>G.add_edges_from([(1,2),(2,3),(3,4),(4,2),(4,5)])<br><br>cycles = list(nx.cycle_basis(G))<br>print(&quot;Cycles in the graph:&quot;, cycles)<br><br>pos = nx.spring_layout(G, seed=42)<br>plt.figure(figsize=(6,5))<br><br>nx.draw_networkx_nodes(G, pos, node_color=&quot;lightblue&quot;, node_size=1000)<br>nx.draw_networkx_edges(G, pos, edge_color=&quot;gray&quot;, width=2)<br>nx.draw_networkx_labels(G, pos, font_size=12, font_weight=&quot;bold&quot;)<br><br># Highlight all cycle edges<br>cycle_edges = []<br>for cycle in cycles:<br>    cycle_edges.extend(list(zip(cycle, cycle[1:] + [cycle[0]])))<br>nx.draw_networkx_edges(G, pos, edgelist=cycle_edges, width=4, edge_color=&quot;red&quot;)<br><br>plt.title(&quot;Undirected Graph Cycles (cycle_basis)&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*jB42C2UGL8r83jynsdvY-A.png" /><figcaption>Undirected Graph Cycles (cycle_basis)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*096p_ewPBuX3cy1sNrqvsw.jpeg" /><figcaption>Undirected Graph Cycles (cycle_basis) Visualization</figcaption></figure><h4>b. Directed Graph Cycles (simple_cycles)</h4><p>nx.simple_cycles(DG) finds <strong>all simple cycles</strong> in a directed graph.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>DG = nx.DiGraph()<br>DG.add_edges_from([(1,2),(2,3),(3,1),(3,4),(4,5)])<br><br>cycles = list(nx.simple_cycles(DG))<br>print(&quot;Cycles in the directed graph:&quot;, cycles)<br><br>pos = nx.spring_layout(DG, seed=42)<br>plt.figure(figsize=(6,5))<br><br>nx.draw_networkx_nodes(DG, pos, node_color=&quot;lightgreen&quot;, node_size=1000)<br>nx.draw_networkx_edges(DG, pos, edge_color=&quot;gray&quot;, width=2, arrows=True, arrowstyle=&#39;-|&gt;&#39;, arrowsize=18)<br>nx.draw_networkx_labels(DG, pos, font_size=12, font_weight=&quot;bold&quot;)<br><br># Highlight all cycles<br>cycle_edges = []<br>for cycle in cycles:<br>    cycle_edges.extend(list(zip(cycle, cycle[1:] + [cycle[0]])))<br>nx.draw_networkx_edges(DG, pos, edgelist=cycle_edges, width=4, edge_color=&quot;red&quot;, arrows=True, arrowstyle=&#39;-|&gt;&#39;, arrowsize=20)<br><br>plt.title(&quot;Directed Graph Cycles (simple_cycles)&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*q5YP9sDgobE3pYtbbwaRcA.png" /><figcaption>Directed Graph Cycles (simple_cycles)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*CnOG3S9ajGDSmyTlNYB9lA.jpeg" /><figcaption>Directed Graph Cycles (simple_cycles) Visualization</figcaption></figure><h4>c. Finding a Single Cycle (find_cycle)</h4><p>nx.find_cycle() is useful when you just want <strong>one cycle</strong>, either in an undirected or directed graph. It raises an exception if no cycle exists.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br># Undirected Graph<br>G = nx.Graph()<br>G.add_edges_from([(1,2),(2,3),(3,4),(4,2),(4,5)])<br><br># Find one cycle in undirected graph<br>try:<br>    cycle_undirected = nx.find_cycle(G)<br>except nx.exception.NetworkXNoCycle:<br>    cycle_undirected = []<br><br># Directed Graph<br>DG = nx.DiGraph()<br>DG.add_edges_from([(1,2),(2,3),(3,1),(3,4),(4,5)])<br><br># Find one cycle in directed graph<br>try:<br>    cycle_directed = nx.find_cycle(DG, orientation=&#39;original&#39;)<br>    cycle_directed_edges = [(u,v) for u,v,d in cycle_directed]<br>except nx.exception.NetworkXNoCycle:<br>    cycle_directed_edges = []<br><br>fig, axes = plt.subplots(1, 2, figsize=(14,6))<br>pos_undirected = nx.spring_layout(G, seed=42)<br>pos_directed = nx.spring_layout(DG, seed=42)<br><br># Undirected Graph<br>nx.draw_networkx_nodes(G, pos_undirected, node_color=&quot;lightblue&quot;, node_size=1000, ax=axes[0])<br>nx.draw_networkx_edges(G, pos_undirected, edge_color=&quot;gray&quot;, width=2, ax=axes[0])<br>nx.draw_networkx_labels(G, pos_undirected, font_size=12, font_weight=&quot;bold&quot;, ax=axes[0])<br>if cycle_undirected:<br>    nx.draw_networkx_edges(G, pos_undirected, edgelist=cycle_undirected, width=4, edge_color=&quot;red&quot;, ax=axes[0])<br>axes[0].set_title(&quot;Single Cycle (Undirected Graph)&quot;)<br>axes[0].axis(&quot;off&quot;)<br><br># Directed Graph<br>nx.draw_networkx_nodes(DG, pos_directed, node_color=&quot;lightgreen&quot;, node_size=1000, ax=axes[1])<br>nx.draw_networkx_edges(DG, pos_directed, edge_color=&quot;gray&quot;, width=2, arrows=True, arrowstyle=&#39;-|&gt;&#39;, arrowsize=18, ax=axes[1])<br>nx.draw_networkx_labels(DG, pos_directed, font_size=12, font_weight=&quot;bold&quot;, ax=axes[1])<br>if cycle_directed_edges:<br>    nx.draw_networkx_edges(DG, pos_directed, edgelist=cycle_directed_edges, width=4, edge_color=&quot;red&quot;, arrows=True, arrowstyle=&#39;-|&gt;&#39;, arrowsize=20, ax=axes[1])<br>axes[1].set_title(&quot;Single Cycle (Directed Graph)&quot;)<br>axes[1].axis(&quot;off&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*gJLd0nJgO8IncALE8-Gwqg.png" /><figcaption>Finding a Single Cycle (find_cycle)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*iPJ68_Sgh28phJ6oIXQqtg.jpeg" /><figcaption>Finding a Single Cycle (find_cycle) Visualization</figcaption></figure><h3>2. Connected Graph Algorithms</h3><p>Connectivity is one of the most important structural properties of graphs. It helps identify whether nodes can reach each other, how many isolated groups exist, and which nodes or edges are critical for keeping the network connected.</p><h4>a. Connectivity in Undirected Graphs</h4><ul><li><strong>nx.is_connected(G)</strong> — Checks if the graph is fully connected</li><li><strong>nx.connected_components(G)</strong> — Returns all connected components</li><li><strong>nx.number_connected_components(G)</strong> — Counts how many connected components exist</li><li><strong>nx.node_connected_component(G, node)</strong> — Returns the component containing a specific node</li><li><strong>nx.bridges(G)</strong> — Finds <em>bridges</em> (edges whose removal disconnects the graph)</li><li><strong>nx.articulation_points(G)</strong> — Finds <em>articulation points</em> (nodes whose removal disconnects the graph)</li></ul><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>G = nx.Graph()<br>G.add_edges_from([<br>    (1,2), (2,3), (3,4),   # Component 1<br>    (5,6)                  # Component 2<br>])<br><br>pos = nx.spring_layout(G, seed=42)<br><br># Connectivity checks<br>print(&quot;Is graph connected?:&quot;, nx.is_connected(G))<br>print(&quot;Number of connected components:&quot;, nx.number_connected_components(G))<br><br>components = list(nx.connected_components(G))<br>print(&quot;Connected components:&quot;, components)<br><br># Component containing specific nodes<br>comp_2 = nx.node_connected_component(G, 2)<br>comp_5 = nx.node_connected_component(G, 5)<br>print(&quot;Component containing node 2:&quot;, comp_2)<br>print(&quot;Component containing node 5:&quot;, comp_5)<br><br># Bridges &amp; articulation points<br>bridges = list(nx.bridges(G))<br>articulation = list(nx.articulation_points(G))<br>print(&quot;Bridges:&quot;, bridges)<br>print(&quot;Articulation Points:&quot;, articulation)<br><br>plt.figure(figsize=(12,6))<br><br>nx.draw_networkx_edges(G, pos, edge_color=&quot;#B0BEC5&quot;, width=2)<br><br>nx.draw_networkx_nodes(G, pos, node_color=&quot;#ECEFF1&quot;, node_size=950, edgecolors=&quot;black&quot;, linewidths=1.2)<br><br>nx.draw_networkx_labels(G, pos, font_size=12, font_weight=&quot;bold&quot;)<br><br># Highlight connected components with distinct colors<br>component_colors = [&quot;#ff9999&quot;, &quot;#99ccff&quot;, &quot;#ffcc99&quot;, &quot;#c299ff&quot;]<br>for i, comp in enumerate(components):<br>    nx.draw_networkx_nodes(G, pos, nodelist=list(comp), node_color=component_colors[i % len(component_colors)], node_size=950, edgecolors=&quot;black&quot;, linewidths=1.5)<br><br># Highlight bridges with bold red edges<br>nx.draw_networkx_edges(G, pos, edgelist=bridges, edge_color=&quot;red&quot;, width=4.5, style=&quot;solid&quot;)<br><br># Highlight articulation points with glowing yellow nodes<br>nx.draw_networkx_nodes(G, pos, nodelist=articulation, node_color=&quot;yellow&quot;, node_size=1100, edgecolors=&quot;black&quot;, linewidths=2)<br><br>plt.title(&quot;Connectivity, Components, Bridges &amp; Articulation Points&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*QKYtviAHBpYzTABOmwL6Eg.png" /><figcaption>Connectivity in Undirected Graphs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bePIc0gtVyvnsD-ICI9o8g.jpeg" /><figcaption>Connectivity in Undirected Graphs Visualization</figcaption></figure><h4>b. Connectivity in Directed Graphs</h4><p>Directed graphs require two types of connectivity:</p><p><strong>Strongly Connected Components (SCCs): </strong>Every node can reach every other <em>via directed paths</em>.</p><p><strong>Weakly Connected Components (WCCs): </strong>Connectivity is checked <em>ignoring direction</em>.</p><ul><li><strong>nx.strongly_connected_components(DG)</strong>- Returns all <strong>Strongly Connected Components (SCCs)</strong></li><li><strong>nx.weakly_connected_components(DG)</strong>- Returns all <strong>Weakly Connected Components (WCCs)</strong></li><li><strong>nx.is_strongly_connected(DG)</strong>- Checks if the entire directed graph is <strong>one strongly connected component</strong>.</li><li><strong>nx.is_weakly_connected(DG)</strong>- Checks if the graph becomes connected when directions are ignored.</li></ul><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>DG = nx.DiGraph()<br>DG.add_edges_from([<br>    (1,2), (2,3), (3,1),   # Strongly Connected Component 1<br>    (4,5)                  # Weakly Connected Component 2<br>])<br><br>pos = nx.spring_layout(DG, seed=42)<br><br># Compute components<br>SCC = list(nx.strongly_connected_components(DG))<br>WCC = list(nx.weakly_connected_components(DG))<br><br>print(&quot;Strongly Connected Components:&quot;, SCC)<br>print(&quot;Weakly Connected Components:&quot;, WCC)<br>print(&quot;Is strongly connected?:&quot;, nx.is_strongly_connected(DG))<br>print(&quot;Is weakly connected?:&quot;, nx.is_weakly_connected(DG))<br><br>plt.figure(figsize=(14,6))<br><br><br># Strongly Connected Components<br>plt.subplot(1, 2, 1)<br>nx.draw_networkx_edges(DG, pos, arrowstyle=&quot;-&gt;&quot;, arrowsize=18, edge_color=&quot;#B0BEC5&quot;, width=2)<br>nx.draw_networkx_labels(DG, pos, font_size=12, font_weight=&quot;bold&quot;)<br><br># Color each SCC<br>scc_colors = [&quot;#ff9999&quot;, &quot;#99ccff&quot;, &quot;#ffcc99&quot;, &quot;#c299ff&quot;]<br>for i, comp in enumerate(SCC):<br>    nx.draw_networkx_nodes(DG, pos, nodelist=list(comp), node_color=scc_colors[i % len(scc_colors)], node_size=900, edgecolors=&quot;black&quot;, linewidths=1.4)<br><br>plt.title(&quot;Strongly Connected Components (SCCs)&quot;, fontsize=14)<br>plt.axis(&quot;off&quot;)<br><br># Weakly Connected Components<br><br>plt.subplot(1, 2, 2)<br>nx.draw_networkx_edges(DG, pos, arrowstyle=&quot;-&gt;&quot;, arrowsize=18, edge_color=&quot;#B0BEC5&quot;, width=2)<br>nx.draw_networkx_labels(DG, pos, font_size=12, font_weight=&quot;bold&quot;)<br><br># Color each WCC<br>wcc_colors = [&quot;#90ee90&quot;, &quot;#ffb3e6&quot;, &quot;#ffe680&quot;]<br>for i, comp in enumerate(WCC):<br>    nx.draw_networkx_nodes(DG, pos, nodelist=list(comp), node_color=wcc_colors[i % len(wcc_colors)], node_size=900, edgecolors=&quot;black&quot;, linewidths=1.4)<br><br>plt.title(&quot;Weakly Connected Components (WCCs)&quot;, fontsize=14)<br>plt.axis(&quot;off&quot;)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*V4uc5ss6r4PcivU_QlmN-Q.png" /><figcaption>Connectivity in Directed Graphs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*JiKlv4UJ1mjxOQfpNzMHyA.jpeg" /><figcaption>Connectivity in Directed Graphs Visualization</figcaption></figure><h3>Conclusion</h3><p>In this guide, you explored how NetworkX helps detect cycles, identify connected components, check connectivity, and find critical structures like bridges and articulation points, all while visualizing graphs clearly. These techniques provide a foundation for more advanced graph analysis, including network resilience, clustering, and structural insights.</p><p>If you haven’t seen the earlier parts of this series, I recommend checking them out — they cover graph creation, traversal, shortest path and minimum spanning trees that make these analyses easier to grasp.</p><p>Stay tuned for the next installment, where we’ll dive deeper into powerful NetworkX tools and real-world graph analysis applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6025c73915d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NetworkX for Python — A Practical Guide to Shortest Paths and Minimum Spanning Trees]]></title>
            <link>https://medium.com/@jainsnehasj6/networkx-for-python-a-practical-guide-to-shortest-paths-and-minimum-spanning-trees-4809e5066596?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/4809e5066596</guid>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[networkx]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 14:26:35 GMT</pubDate>
            <atom:updated>2025-12-18T14:26:35.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>NetworkX for Python — A Practical Guide to Shortest Paths and Minimum Spanning Trees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScipFJJSGb01c0mYULS6jQ.png" /></figure><p>In this part of the series, we dive into two core graph concepts: <strong>shortest paths</strong> and <strong>minimum spanning trees</strong>. Using NetworkX, you’ll learn how popular algorithms like Dijkstra, Bellman–Ford, A*, Kruskal, and Prim work — and how to visualize them for clear, practical insight.</p><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installation</h3><pre>pip install networkx</pre><h3>1. Shortest Path Algorithms</h3><p>The <strong>shortest path</strong> between two nodes is:</p><ul><li><strong>Unweighted graph: </strong>The path with the <strong>minimum number of edges</strong>.</li><li><strong>Weighted graph: </strong>The path with the <strong>minimum total weight</strong>.</li></ul><h4>a. Shortest Path in Unweighted Graphs (BFS)</h4><p>For unweighted graphs, shortest paths are found using <strong>Breadth-First Search</strong>.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>G = nx.Graph()<br>G.add_edges_from([(1,2),(2,3),(3,4),(4,5),(2,5)])<br><br>path = nx.shortest_path(G, source=1, target=5)<br>dist = nx.shortest_path_length(G, source=1, target=5)<br><br>print(&quot;Shortest Path:&quot;, path)<br>print(&quot;Distance:&quot;, dist)<br><br>pos = nx.spring_layout(G)<br>plt.figure(figsize=(6,4))<br><br>nx.draw(G, pos, with_labels=True, node_color=&quot;lightblue&quot;, edge_color=&quot;gray&quot;, node_size=1200)<br><br>edge_list = list(zip(path, path[1:]))<br>nx.draw_networkx_edges(G, pos, edgelist=edge_list, width=3)<br><br>plt.title(&quot;Shortest Path in Unweighted Graph (BFS)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*5vQ68T-aq2fq3q4X9sNcEw.png" /><figcaption>Shortest Path in Unweighted Graphs (BFS)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*5BMYj1X0Wi1pOUDJN9qCFw.jpeg" /><figcaption>Shortest Path in Unweighted Graphs (BFS) Visualization</figcaption></figure><h4>b. Weighted Shortest Paths (Dijkstra)</h4><p>When edges have weights, NetworkX uses <strong>Dijkstra’s Algorithm</strong> by default (if all weights are positive).</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>WG = nx.Graph()<br>WG.add_weighted_edges_from([(1,2,4),(2,3,1),(1,3,7),(3,4,2)])<br><br>path = nx.dijkstra_path(WG, source=1, target=4)<br>dist = nx.dijkstra_path_length(WG, source=1, target=4)<br><br>print(&quot;Shortest Weighted Path:&quot;, path)<br>print(&quot;Total Weight:&quot;, dist)<br><br>plt.figure(figsize=(8,6))<br><br>pos = nx.spring_layout(WG, seed=42)<br><br># Color all nodes<br>nx.draw_networkx_nodes(WG, pos, node_color=&quot;lightgray&quot;, node_size=1200)<br><br># Highlight nodes in path<br>nx.draw_networkx_nodes(WG, pos, nodelist=path, node_color=&quot;#ffcc00&quot;, node_size=1400)<br><br># Draw full graph edges<br>nx.draw_networkx_edges(WG, pos, edge_color=&quot;gray&quot;, width=2)<br><br># Highlight shortest path edges<br>path_edges = list(zip(path, path[1:]))<br>nx.draw_networkx_edges(WG, pos, edgelist=path_edges, width=4, edge_color=&quot;red&quot;)<br><br># Draw labels<br>nx.draw_networkx_labels(WG, pos, font_size=12, font_weight=&quot;bold&quot;)<br><br># Draw weight labels<br>edge_labels = nx.get_edge_attributes(WG, &#39;weight&#39;)<br>nx.draw_networkx_edge_labels( WG, pos, edge_labels=edge_labels, font_color=&quot;blue&quot;, font_size=11)<br><br>plt.title(&quot;Dijkstra&#39;s Shortest Path (Weighted Graph)&quot;, fontsize=14)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*pXo3s7crvdAAMQ5UeWfCPQ.png" /><figcaption>Weighted Shortest Paths (Dijkstra)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hBK3PoKQDOH8yboMKQsu2w.jpeg" /><figcaption>Weighted Shortest Paths (Dijkstra) Visualization</figcaption></figure><h4>c. Bellman–Ford Shortest Path</h4><p>Bellman–Ford is used for <strong>graphs with negative edge weights</strong> (as long as there’s no negative cycle).</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>G = nx.DiGraph()<br>G.add_weighted_edges_from([(1, 2, 6),(1, 3, 5),(1, 4, 5),(2, 5, -1),(3, 2, -2),(3, 5, 3),(4, 6, -1),(5, 6, 3)])<br><br>path = nx.bellman_ford_path(G, source=1, target=6)<br>dist = nx.bellman_ford_path_length(G, source=1, target=6)<br><br>print(&quot;Bellman-Ford Path:&quot;, path)<br>print(&quot;Total Weight:&quot;, dist)<br><br>plt.figure(figsize=(10,7))<br><br>pos = nx.spring_layout(G, seed=42, k=0.5)<br><br># Draw nodes<br>nx.draw_networkx_nodes(G, pos, node_color=&quot;#e8eaf6&quot;, node_size=1000, edgecolors=&quot;black&quot;)<br><br># Highlight path nodes<br>nx.draw_networkx_nodes(G, pos, nodelist=path, node_color=&quot;#ffeb3b&quot;, node_size=1200, edgecolors=&quot;black&quot;)<br><br># Draw all edges<br>nx.draw_networkx_edges(G, pos, edge_color=&quot;gray&quot;, width=2, arrows=True, arrowstyle=&#39;-|&gt;&#39;, arrowsize=18)<br><br># Highlight the shortest path edges<br>path_edges = list(zip(path, path[1:]))<br>nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color=&quot;red&quot;, width=3.5, arrows=True, arrowstyle=&#39;-|&gt;&#39;, arrowsize=22)<br><br># Draw labels<br>nx.draw_networkx_labels(G, pos, font_size=12, font_weight=&quot;bold&quot;)<br><br># Draw edge weight labels<br>edge_labels = nx.get_edge_attributes(G, &#39;weight&#39;)<br>nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=11, font_color=&quot;blue&quot;, label_pos=0.6)<br><br>plt.title(&quot;Bellman–Ford Shortest Path&quot;, fontsize=15)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*NTET6mztdO83VUHvUPiLrw.png" /><figcaption>Bellman–Ford Shortest Path</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*AU6I9GyXMMwkynaEaZ1Yuw.jpeg" /><figcaption>Bellman–Ford Shortest Path Visualization</figcaption></figure><h4>d. A* Algorithm</h4><p>A* is great for <strong>spatial or coordinate-based shortest paths</strong> because it uses a <strong>heuristic</strong>.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br>import math<br><br># Euclidean distance heuristic<br>def heuristic(a, b):<br>    return math.dist(a, b)<br><br># Graph with coordinates as nodes<br>G = nx.Graph()<br>G.add_edge((0,0), (1,0), weight=1)<br>G.add_edge((1,0), (1,1), weight=1)<br>G.add_edge((0,0), (1,1), weight=1.4)  <br><br>start = (0,0)<br>goal = (1,1)<br><br># Compute A* shortest path<br>path = nx.astar_path(G, start, goal, heuristic=heuristic)<br>print(&quot;A* Path:&quot;, path)<br><br>pos = {node: node for node in G.nodes()}  <br><br>plt.figure(figsize=(6,5))<br><br># Draw all nodes and edges<br>nx.draw(G, pos, with_labels=True, node_color=&quot;lightgreen&quot;, node_size=1000)<br><br># Draw edge weights<br>labels = nx.get_edge_attributes(G, &#39;weight&#39;)<br>nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)<br><br># Highlight the A* path<br>path_edges = list(zip(path, path[1:]))<br>nx.draw_networkx_edges(G, pos, edgelist=path_edges, width=3, edge_color=&quot;red&quot;)<br><br># Highlight path nodes<br>nx.draw_networkx_nodes(G, pos, nodelist=path, node_color=&quot;yellow&quot;, node_size=1200)<br><br>plt.title(&quot;A* Search Shortest Path (Euclidean Heuristic)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*xvY9ntt4jDV456AjQNa1Cg.png" /><figcaption>A* Algorithm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*P2j20o2QPmpFksNWA-DuIQ.jpeg" /><figcaption>A* Algorithm Visualization</figcaption></figure><h3>2. Minimum Spanning Tree</h3><ul><li>A <strong>spanning tree</strong> connects all nodes of a graph without creating cycles.</li><li>A <strong>minimum spanning tree</strong> is the spanning tree with the <strong>smallest possible sum of edge weights</strong>.</li></ul><h4>a. Kruskal’s Algorithm</h4><p>Kruskal’s algorithm builds the MST by <strong>sorting all edges by weight</strong> and adding them one by one, avoiding cycles.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>G = nx.Graph()<br>G.add_weighted_edges_from([(1, 2, 4), (1, 3, 1), (2, 3, 3), (2, 4, 2), (3, 4, 5)])<br><br>mst = nx.minimum_spanning_tree(G, algorithm=&#39;kruskal&#39;)<br><br>total_weight = sum(nx.get_edge_attributes(mst, &#39;weight&#39;).values())<br>print(&quot;Edges in MST:&quot;, list(mst.edges(data=True)))<br>print(&quot;Total weight:&quot;, total_weight)<br><br>pos = nx.spring_layout(G, seed=42)<br>plt.figure(figsize=(7,5))<br><br># Draw all nodes<br>nx.draw_networkx_nodes(G, pos, node_color=&quot;lightblue&quot;, node_size=1000)<br><br># Draw all edges in gray<br>nx.draw_networkx_edges(G, pos, edge_color=&quot;gray&quot;, width=2)<br><br># Highlight MST edges<br>nx.draw_networkx_edges(G, pos, edgelist=mst.edges(), width=4, edge_color=&quot;red&quot;)<br><br># Labels<br>nx.draw_networkx_labels(G, pos, font_size=12, font_weight=&quot;bold&quot;)<br>edge_labels = nx.get_edge_attributes(G, &#39;weight&#39;)<br>nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color=&quot;blue&quot;)<br><br>plt.title(&quot;Minimum Spanning Tree (Kruskal&#39;s Algorithm)&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*gyjnUquMu0PYsn2G8dQngg.png" /><figcaption>Minimum Spanning Tree (Kruskal’s Algorithm)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*bxfpXw0-FEF8z9wKGxBkQg.jpeg" /><figcaption>Minimum Spanning Tree (Kruskal’s Algorithm) Visualization</figcaption></figure><h4>b. Prim’s Algorithm</h4><p>Prim’s algorithm grows the MST from a <strong>starting node</strong>, always adding the <strong>smallest edge connecting the tree to a new node</strong>.</p><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br>G = nx.Graph()<br>G.add_weighted_edges_from([(1, 2, 4), (1, 3, 1), (2, 3, 3), (2, 4, 2), (3, 4, 5)])<br><br>mst = nx.minimum_spanning_tree(G, algorithm=&#39;prim&#39;)<br><br>total_weight = sum(nx.get_edge_attributes(mst, &#39;weight&#39;).values())<br>print(&quot;Edges in MST:&quot;, list(mst.edges(data=True)))<br>print(&quot;Total weight:&quot;, total_weight)<br><br>pos = nx.spring_layout(G, seed=42)<br>plt.figure(figsize=(7,5))<br><br># Draw all nodes<br>nx.draw_networkx_nodes(G, pos, node_color=&quot;lightblue&quot;, node_size=1000)<br><br># Draw all edges in gray<br>nx.draw_networkx_edges(G, pos, edge_color=&quot;gray&quot;, width=2)<br><br># Highlight MST edges<br>nx.draw_networkx_edges(G, pos, edgelist=mst.edges(), width=4, edge_color=&quot;red&quot;)<br><br># Labels<br>nx.draw_networkx_labels(G, pos, font_size=12, font_weight=&quot;bold&quot;)<br>edge_labels = nx.get_edge_attributes(G, &#39;weight&#39;)<br>nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_color=&quot;blue&quot;)<br><br>plt.title(&quot;Minimum Spanning Tree (Prim&#39;s Algorithm)&quot;)<br>plt.axis(&quot;off&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*OcNRZQTkwpv-PQ6Mq_cyxQ.png" /><figcaption>Minimum Spanning Tree (Prim’s Algorithm)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*HlEohKolXzqyC6OVTELb1A.jpeg" /><figcaption>Minimum Spanning Tree (Prim’s Algorithm) Visualization</figcaption></figure><blockquote><em>Both Kruskal’s and Prim’s produce the </em><strong><em>same MST</em></strong><em>, but the process differs: Kruskal considers </em><strong><em>edges globally</em></strong><em>, while Prim grows the tree </em><strong><em>locally</em></strong><em>.</em></blockquote><h3>Conclusion</h3><p>In this guide, you explored how NetworkX handles <strong>shortest paths</strong> and <strong>minimum spanning trees</strong>, two of the most important building blocks in graph analytics. These techniques open the door to more advanced topics such as centrality, clustering, and network optimization.</p><p>If you haven’t read the <strong>first part of this series</strong>, I recommend checking it out — it covers graph creation, traversal basics, and core concepts that build a strong foundation for everything discussed here.</p><p>Stay tuned for the next installment, where we’ll continue exploring more powerful NetworkX tools and real-world graph analysis patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4809e5066596" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NetworkX for Python — A Practical Guide to Graphs, Visualization, and Traversals]]></title>
            <link>https://medium.com/@jainsnehasj6/networkx-for-python-a-practical-guide-to-graphs-visualization-and-traversals-35106cfee2ea?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/35106cfee2ea</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[networkx]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 06:14:18 GMT</pubDate>
            <atom:updated>2025-12-07T06:14:18.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>NetworkX for Python — A Practical Guide to Graphs, Visualization, and Traversals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ya1hntBq5CjNdbMuWL7j5A.png" /></figure><p>NetworkX is a Python library designed for the creation, manipulation, and study of complex networks of nodes and edges. It supports:</p><ul><li><strong>Graph types:</strong> undirected, directed, multigraphs.</li><li><strong>Algorithms:</strong> shortest paths, clustering, centrality, and more.</li><li><strong>Data structures:</strong> flexible handling of nodes and edges.</li><li><strong>Visualization: </strong>integration with Matplotlib and Plotly</li></ul><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installation</h3><pre>pip install networkx</pre><h3>Basic Import</h3><pre>import networkx as nx<br>import matplotlib.pyplot as plt</pre><h3>1. Graph Types in NetworkX</h3><p>NetworkX provides several graph types:</p><ol><li><strong>Graph</strong> → Undirected graph (single edge between nodes)</li><li><strong>DiGraph</strong> → Directed graph (single directed edge)</li><li><strong>MultiGraph</strong> → Undirected graph that allows <strong>multiple parallel edge.</strong></li><li><strong>MultiDiGraph</strong> → Directed graph that allows <strong>multiple directed parallel edges</strong></li></ol><pre># Undirected Graph<br>G = nx.Graph()<br><br># Directed Graph<br>DG = nx.DiGraph()<br><br># Multigraph<br>MG = nx.MultiGraph()<br><br># Directed Multigraph<br>DMG = nx.MultiDiGraph()</pre><h3>2. Creating Graphs</h3><h4>a. Adding Nodes and Edges</h4><pre>G = nx.Graph()<br><br># Add nodes<br>G.add_node(1)<br>G.add_nodes_from([2, 3, 4])<br><br># Add edges<br>G.add_edge(1, 2)<br>G.add_edges_from([(2, 3), (3, 4)])<br><br>print(&quot;Nodes:&quot;, G.nodes())<br>print(&quot;Edges:&quot;, G.edges())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*wSY56KgGrFlgMlP_xQh_8g.png" /><figcaption>Edges &amp; Nodes</figcaption></figure><h4>b. Adding Attributes</h4><pre># Node attributes<br>names = {1: &#39;Alice&#39;, 2: &#39;Bob&#39;, 3: &#39;Charlie&#39;, 4: &#39;Diana&#39;}<br>for node, name in names.items():<br>    G.nodes[node][&#39;name&#39;] = name<br><br># Edge attributes<br>weights = {(1, 2): 4.5, (2, 3): 5, (3, 4): 6.2}<br>for edge, weight in weights.items():<br>    G.edges[edge][&#39;weight&#39;] = weight<br><br>print(G.nodes(data=True))<br>print(G.edges(data=True))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*3dTa_csYLjlMfnYZF5rA0Q.png" /><figcaption>Adding Attributes</figcaption></figure><h3>3. Graph Visualization</h3><p>NetworkX integrates with Matplotlib for simple graph visualization.</p><h4>a. Simple Visualization with Edges and Nodes</h4><pre>nx.draw(G, with_labels=True, node_color=&#39;lightblue&#39;, edge_color=&#39;gray&#39;, node_size=1500)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*hMFOTxX7JovM18I-14NoDA.jpeg" /><figcaption>Simple Visualization with Edges and Nodes</figcaption></figure><h4>b. Visualization with Attributes</h4><pre>pos = nx.spring_layout(G) <br>nx.draw(G, pos, node_color=&#39;lightblue&#39;, edge_color=&#39;gray&#39;, node_size=2500, with_labels=False)<br><br>node_labels = {node: G.nodes[node].get(&#39;name&#39;, node) for node in G.nodes()}<br>nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=12, font_weight=&#39;bold&#39;)<br><br>edge_labels = nx.get_edge_attributes(G, &#39;weight&#39;)<br>nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*ehVWGlIlJEomKUj-bq4PDg.jpeg" /><figcaption>Visualization with Attributes</figcaption></figure><p>For more advanced visualization, libraries like <strong>PyVis</strong> or <strong>Plotly</strong> can be used.</p><h3>4. Directed Graph</h3><p>Directed graphs have edges with direction.</p><pre>import networkx as nx<br><br>DG = nx.DiGraph()<br>DG.add_edges_from([(1, 2), (2, 3), (3, 1)])<br><br>print(&quot;Nodes:&quot;, DG.nodes())<br>print(&quot;Edges:&quot;, DG.edges())<br><br># In-degree and out-degree<br>print(&quot;In-degree:&quot;, DG.in_degree())<br>print(&quot;Out-degree:&quot;, DG.out_degree())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*K1i2Lr6KrRgTxo9XWUdZrQ.png" /><figcaption>DiGraph</figcaption></figure><pre>import matplotlib.pyplot as plt<br><br>nx.draw(DG, with_labels=True, node_color=&#39;lightblue&#39;, arrows=True, node_size=1200)<br>plt.title(&quot;Directed Graph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*yVDNSaVTrlCGBdwoguo0HQ.jpeg" /><figcaption>DiGraph Visualization</figcaption></figure><h3>5. Undirected Multigraph</h3><p>MultiGraph allows <strong>multiple edges between the same nodes</strong> (undirected).</p><pre>import networkx as nx<br><br>MG = nx.MultiGraph()<br>MG.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 2)])  <br><br>print(&quot;MultiGraph Nodes:&quot;, MG.nodes())<br>print(&quot;MultiGraph Edges:&quot;, MG.edges())<br>print(&quot;MultiGraph Edge Count:&quot;, MG.number_of_edges())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*i7GFeQOEQekAeOd4aqIVrg.png" /><figcaption>Undirected Multigraph</figcaption></figure><pre>import matplotlib.pyplot as plt<br><br>pos = nx.spring_layout(MG)<br>nx.draw(MG, pos, with_labels=True, node_color=&#39;lightgreen&#39;, edge_color=&#39;gray&#39;, node_size=1500)<br>plt.title(&quot;Undirected MultiGraph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*OAVxVkvHt1q91sS-O7zUdQ.jpeg" /><figcaption>Undirected Multigraph Visualization</figcaption></figure><h3>6. Directed Multigraph</h3><p>MultiDiGraph allows <strong>multiple directed edges</strong> between the same nodes.</p><pre>import networkx as nx<br><br>DMG = nx.MultiDiGraph()<br>DMG.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 2)])<br><br>print(&quot;MultiDiGraph Nodes:&quot;, DMG.nodes())<br>print(&quot;MultiDiGraph Edges:&quot;, DMG.edges())<br>print(&quot;MultiDiGraph Edge Count:&quot;, DMG.number_of_edges())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*AE4w41OLThxnvdJDnEJa6A.png" /><figcaption>Directed Multigraph</figcaption></figure><pre>import matplotlib.pyplot as plt<br><br>pos = nx.spring_layout(DMG)<br>nx.draw(DMG, pos, with_labels=True, node_color=&#39;lightcoral&#39;, edge_color=&#39;gray&#39;, node_size=1500, arrows=True)<br>plt.title(&quot;Directed MultiDiGraph&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Y0V5SDWQMaWuheT4IFoVCQ.jpeg" /><figcaption>Directed MultiDiGraph</figcaption></figure><h3>7. Traversals</h3><h4>a. Depth-First Search (DFS)</h4><p><strong>Depth-First Search (DFS)</strong> explores a graph by going <strong>as deep as possible</strong> along one path before backtracking.</p><pre>import networkx as nx<br><br>G = nx.Graph()<br>G.add_edges_from([(1,2),(1,3),(2,4),(2,5),(5,3),(5,6),(6,7)])<br><br># DFS edges starting from node 1<br>dfs_edges = list(nx.dfs_edges(G, source=1))<br>print(&quot;DFS Edges:&quot;, dfs_edges)<br><br># DFS Traversal Order (Nodes)<br>dfs_nodes = list(nx.dfs_preorder_nodes(G, source=1))<br>print(&quot;DFS Node Order:&quot;, dfs_nodes)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*vImcIIs4v-PwjyPr_5yBYw.png" /><figcaption>DFS Traversal</figcaption></figure><p>DFS goes <strong>deep first</strong>: <strong>1 → 2 → 4 → backtrack → 5 → 6 → 7 → backtrack → 3</strong></p><pre>import matplotlib.pyplot as plt<br><br>dfs_tree = nx.dfs_tree(G, source=1)<br>dfs_edges = list(dfs_tree.edges())<br><br>pos = nx.spring_layout(G, seed=42)<br><br>plt.figure(figsize=(7,6))<br><br># Draw the full graph<br>nx.draw(G, pos, with_labels=True, node_color=&quot;lightblue&quot;, edge_color=&quot;gray&quot;, node_size=1200)<br><br># Highlight DFS edges<br>nx.draw_networkx_edges(G, pos, edgelist=dfs_edges, edge_color=&quot;red&quot;, width=3)<br><br>plt.title(&quot;DFS Tree Starting from Node 1&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*MMiFLPt4DuSsSamrgkYkMw.jpeg" /><figcaption>Visualization of DFS Traversal</figcaption></figure><h4>b. Breadth-First Search (BFS)</h4><p>It is a traversal algorithm that explores <strong>all neighbors of a node before moving to the next level</strong>.</p><pre>import networkx as nx<br><br>G = nx.Graph()<br>G.add_edges_from([(1,2),(1,3),(2,4),(2,5),(5,3),(5,6),(6,7)])<br><br># BFS edges starting from node 1<br>bfs_edges = list(nx.bfs_edges(G, source=1))<br>print(&quot;BFS Edges:&quot;, bfs_edges)<br><br># BFS Traversal Order (Nodes)<br>bfs_nodes = list(nx.bfs_tree(G, source=1))<br>print(&quot;BFS Node Order:&quot;, bfs_nodes)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*hlS6Z1qUREViCK6M3aINpw.png" /><figcaption>BFS Traversal</figcaption></figure><p>BFS expands <strong>breadth-first</strong>: <strong>1 → (2, 3) → (4, 5) → (6) → (7)</strong></p><pre>import matplotlib.pyplot as plt<br><br>bfs_tree = nx.bfs_tree(G, source=1)<br>bfs_edges = list(bfs_tree.edges())<br><br>pos = nx.spring_layout(G, seed=42)<br><br>plt.figure(figsize=(7,6))<br><br># Draw the full graph<br>nx.draw(G, pos, with_labels=True, node_color=&quot;lightblue&quot;, edge_color=&quot;gray&quot;, node_size=1200)<br><br># Highlight BFS edges<br>nx.draw_networkx_edges(G, pos, edgelist=bfs_edges, edge_color=&quot;red&quot;, width=3)<br><br>plt.title(&quot;BFS Tree Starting from Node 1&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*1B_i_SmYrHrADHaDVAkb-g.jpeg" /><figcaption>Visualization of BFS Traversal</figcaption></figure><h3>Bonus — Types of Graphs Visualization Cheat Sheet</h3><pre>import networkx as nx<br>import matplotlib.pyplot as plt<br><br># 1. Undirected Graph<br>G = nx.Graph()<br>G.add_edges_from([(1, 2), (2, 3), (3, 4)])<br><br># 2. Directed Graph<br>DG = nx.DiGraph()<br>DG.add_edges_from([(1, 2), (2, 3), (3, 1)])<br><br># 3. Undirected MultiGraph<br>MG = nx.MultiGraph()<br>MG.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 2)])<br><br># 4. Directed MultiDiGraph<br>DMG = nx.MultiDiGraph()<br>DMG.add_edges_from([(1, 2), (2, 3), (3, 1), (1, 2)])<br><br>fig, axes = plt.subplots(2, 2, figsize=(12, 10))<br><br>posG   = nx.spring_layout(G, seed=10)<br>posDG  = nx.spring_layout(DG, seed=10)<br>posMG  = nx.spring_layout(MG, seed=10)<br>posDMG = nx.spring_layout(DMG, seed=10)<br><br>def draw_graph(ax, graph, pos, title, color, directed=False):<br>    nx.draw(graph, pos, with_labels=True, node_color=color, node_size=1500, edge_color=&#39;gray&#39;, arrows=directed, clip_on=False, ax=ax)<br>    ax.set_title(title, fontsize=14)<br>    ax.margins(0.2)        <br>    ax.set_axis_off()<br><br>draw_graph(axes[0,0], G, posG,   &quot;Undirected Graph&quot;,          &quot;lightblue&quot;)<br>draw_graph(axes[0,1], DG, posDG, &quot;Directed Graph (DiGraph)&quot;,  &quot;lightgreen&quot;, directed=True)<br>draw_graph(axes[1,0], MG, posMG, &quot;Undirected MultiGraph&quot;,     &quot;lightcoral&quot;)<br>draw_graph(axes[1,1], DMG, posDMG,&quot;Directed MultiDiGraph&quot;,    &quot;orange&quot;, directed=True)<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2R-oBJESJGRFDmFANg5hQ.png" /><figcaption>Types of Graphs Visualization Cheat Sheet</figcaption></figure><h3>Conclusion</h3><p>In this guide, you learned how to build, explore, and visualize graphs using NetworkX — from creating nodes and edges to understanding different types of graph &amp; traversals. These fundamentals form the backbone of practical graph analysis and prepare you for more advanced techniques.</p><p><strong>Stay tuned for the next part, where you’ll dive into powerful NetworkX algorithms.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35106cfee2ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate alive-progress Guide: Beautiful Animated Progress Bars for Python]]></title>
            <link>https://medium.com/@jainsnehasj6/the-ultimate-alive-progress-guide-beautiful-animated-progress-bars-for-python-ff08e92950af?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff08e92950af</guid>
            <category><![CDATA[progress-bar]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 05:04:45 GMT</pubDate>
            <atom:updated>2025-11-17T05:04:45.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yY4Qs7z_iZa5_Ku5KdEaoQ.png" /></figure><p>alive-progress is a Python library for creating visually appealing progress bars (and spinners) in the terminal, designed especially for CLI scripts, loops, and longer-running tasks. It has some nice extras compared to many simpler progress bars: animations, throughput display (iterations/sec), ETA (“time remaining”), logging/print hooks, suspend/resume support, etc.</p><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installing Library</h3><pre>pip install alive-progress</pre><h3>Basic Bar</h3><pre>from alive_progress import alive_bar<br>import time<br><br>items = list(range(1000))<br>with alive_bar(len(items)) as bar:<br>    for item in items:<br>        time.sleep(0.005)<br>        bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A0MQ-PhyidR19T12FMsMXg.gif" /><figcaption>Basic Bar</figcaption></figure><h3>Using alive_it() – the EASIEST loop wrapper</h3><pre>from alive_progress import alive_it<br>import time<br><br>for item in alive_it(range(300), title=&quot;Auto Progress&quot;):<br>    time.sleep(0.01)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKiSCLPl1UpKTBMlIH7xnQ.gif" /><figcaption>Using alive_it()</figcaption></figure><h3>Set Inline Message</h3><p>Inline message can be added using bar.text(&#39;message&#39;) or bar.text = &#39;message&#39;</p><pre>from alive_progress import alive_bar<br>import time<br><br>items = list(range(1000))<br>with alive_bar(len(items)) as bar:<br>    for item in items:<br>        bar.text = f&quot;Processing item {item}&quot;<br>        time.sleep(0.003)<br>        bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPqLqkTKUxk5bueD89w9TA.gif" /><figcaption>Set Inline Message</figcaption></figure><h3>Set Title</h3><p>Title can be added using title = [“YOUR_TITLE”].</p><pre>from time import sleep<br>from alive_progress import alive_bar<br><br>total = 500<br>with alive_bar(total, title=&#39;Loading&#39;) as bar:<br>    for _ in range(total):<br>        sleep(0.01)<br>        bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOg70GhgibA5cPDELBvabA.gif" /><figcaption>Set Title</figcaption></figure><h3>Change bar style</h3><p>You can explore bar styles via from alive_progress.styles import showtime and run showtime() to preview available bar styles.</p><pre>from alive_progress.styles import showtime, Show<br><br>showtime(Show.BARS)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHm9suM8xnyXFiaGkQrzRw.gif" /><figcaption>Bar Examples</figcaption></figure><p>The bar style can be changed using bar=[‘YOUR_CHOICE”] from the list above.</p><pre>from time import sleep<br>from alive_progress import alive_bar<br><br>total = 500<br>with alive_bar(total, bar=&#39;bubbles&#39;) as bar:<br>    for _ in range(total):<br>        sleep(0.01)<br>        bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYE5UZfHSB6YK9wUk3KENA.gif" /><figcaption>bar=’bubbles’</figcaption></figure><h3>Change Spinner style</h3><p>You can explore spinner styles via from alive_progress.styles import showtimeand run showtime() to preview available spinner styles.</p><pre>from alive_progress.styles import showtime, Show<br><br>showtime(Show.SPINNERS)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09YjPXfrmEXzQz50-flYfA.gif" /><figcaption>Spinner examples</figcaption></figure><p>The spinner style can be changed using spinner=[‘YOUR_CHOICE’] from the list above.</p><pre>from time import sleep<br>from alive_progress import alive_bar<br><br>total = 500<br>with alive_bar(total, spinner=&#39;dots_waves&#39;) as bar:<br>    for _ in range(total):<br>        sleep(0.01)<br>        bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qu1oDMWXgVC2woazorUyuQ.gif" /><figcaption>spinner=’dots_waves’</figcaption></figure><h3>Nested Progress Bars</h3><pre>from alive_progress import alive_bar<br>import time<br><br>outer_total = 3<br>inner_total = 50<br><br>with alive_bar(outer_total * inner_total, title=&quot;Main Task&quot;) as bar:<br><br>    for i in range(outer_total):<br>        for j in range(inner_total):<br>            bar.text = f&quot;Outer {i+1}/{outer_total} | Inner {j+1}/{inner_total}&quot;<br>            time.sleep(0.05)<br>            bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBVAh6CZXcKSrmoSaAp0XA.gif" /><figcaption>Nested Progress Bars</figcaption></figure><h3>Print/log hooking</h3><pre>from alive_progress import alive_bar<br>import time<br><br>with alive_bar(200) as bar:<br>    for i in range(200):<br>        if i % 50 == 0:<br>            print(f&quot;Milestone: reached {i}&quot;)<br>        time.sleep(0.01)<br>        bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fOpSVemg-t2-HT5rEeePg.gif" /><figcaption>Print/log hooking</figcaption></figure><h3>Suspend / Resume</h3><pre>from alive_progress import alive_bar<br>import time<br><br>with alive_bar(500) as bar:<br>    for i in range(200):<br>        time.sleep(0.02)<br>        bar()<br>    input(&quot;Paused – press Enter to continue…&quot;)<br>    for i in range(200,500):<br>        time.sleep(0.02)<br>        bar()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfQOiFgq4jXNtHMwKwHA1w.gif" /><figcaption>Suspend / Resume</figcaption></figure><h3>Manual Mode (Set exact percentage yourself)</h3><pre>from alive_progress import alive_bar<br>import time<br><br>with alive_bar(manual=True, title=&quot;Manual Progress&quot;) as bar:<br>    for pct in [0.1, 0.25, 0.5, 0.75, 1]:<br>        bar(pct)<br>        time.sleep(0.8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTLKPX1SEjXNeHl4Y7jxEQ.gif" /><figcaption>Manual Mode</figcaption></figure><h3>Accessing Final Receipt</h3><pre>from alive_progress import alive_bar<br>import time<br><br>with alive_bar(100) as bar:<br>    for i in range(100):<br>        time.sleep(0.01)<br>        bar()<br><br>print(&quot;Final Receipt:&quot;)<br>print(bar.receipt)  <br>print(&quot;Elapsed:&quot;, bar.elapsed)<br>print(&quot;Throughput:&quot;, bar.rate)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--fM4XwJRAWKMDW25JPLrg.gif" /><figcaption>Accessing Final Receipt</figcaption></figure><h3>Showing Success Message at the End</h3><pre>from alive_progress import alive_bar<br>import time<br><br>with alive_bar(50, title=&quot;Task Running&quot;) as bar:<br>    for _ in range(50):<br>        time.sleep(0.02)<br>        bar()<br><br>print(&quot;\n✔ Task completed successfully!&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-CEOFGnJ8asTSfjHj4BJw.gif" /><figcaption>Showing Success Message at the End</figcaption></figure><h3>Bonus 1 — Live Temperature Simulation</h3><pre>import time<br>import random<br>from alive_progress import alive_bar<br><br>with alive_bar(300, manual=True, title=&quot;Sensor Reading&quot;) as bar:<br>    for _ in range(300):<br>        temp = random.uniform(20, 35)<br>        bar((temp - 20) / 15)<br>        bar.text = f&quot;Temperature: {temp:.2f}°C&quot;<br>        time.sleep(0.05)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ldrFsdXmwyIXbTUmOXx6g.gif" /><figcaption>Live Temperature Simulation</figcaption></figure><h3>Bonus 2— Multi-Task Dashboard</h3><pre>from alive_progress import alive_bar<br>import time<br><br>def task(name, total, delay):<br>    with alive_bar(total, title=name, bar=&#39;smooth&#39;, spinner=&#39;dots&#39;) as bar:<br>        for _ in range(total):<br>            time.sleep(delay)<br>            bar()<br><br>task(&quot;Fetching Data&quot;, 120, 0.01)<br><br>task(&quot;Cleaning &amp; Preprocessing&quot;, 80, 0.02)<br><br>task(&quot;Saving Results&quot;, 40, 0.03)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezYlJe3I5JS2CgUy3Bzr2Q.gif" /><figcaption>Multi-Task Dashboard</figcaption></figure><h3>Conclusion</h3><p>The alive-progress library is one of the most powerful and visually appealing progress bar tools available for Python developers.</p><p>Its flexibility makes it ideal for:</p><p>✔ Data processing scripts<br> ✔ Machine learning pipelines<br> ✔ File operations<br> ✔ Automation tools<br> ✔ CLI applications<br> ✔ Debugging long loops</p><p>Stay tuned for the next library drop in this series!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff08e92950af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Tabulate in Python: Create Beautiful Tables Effortlessly]]></title>
            <link>https://medium.com/@jainsnehasj6/mastering-tabulate-in-python-create-beautiful-tables-effortlessly-50f70a75862c?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/50f70a75862c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tabulate]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[dataframes]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 15:09:20 GMT</pubDate>
            <atom:updated>2025-11-04T08:33:33.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NRWElBjPQMP9Makf" /></figure><p>Welcome back to the series where we explore Python libraries that make data presentation both simple and beautiful. Today, we’re looking at <strong>Tabulate</strong> — a lightweight Python library that turns your lists or DataFrames into neatly formatted tables with just a few lines of code.</p><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installing Library</h3><pre>pip install tabulate</pre><h3>Basic Table</h3><pre>from tabulate import tabulate<br><br>data = [<br>    [&quot;Apple&quot;, 10],<br>    [&quot;Banana&quot;, 5],<br>    [&quot;Orange&quot;, 8],<br>    [&quot;Grapes&quot;, 12],<br>    [&quot;Mango&quot;, 7]<br>]<br><br>print(tabulate(data))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*Z07Do8tXnR_ezZ3HKxTnwA.png" /><figcaption>Basic table</figcaption></figure><h3>Adding Headers</h3><h4>1. Supply a list of header names</h4><pre>from tabulate import tabulate<br><br>headers = [&quot;Country&quot;, &quot;Capital&quot;, &quot;Population (M)&quot;]<br>data = [<br>    [&quot;France&quot;, &quot;Paris&quot;, 67],<br>    [&quot;Japan&quot;, &quot;Tokyo&quot;, 126],<br>    [&quot;Canada&quot;, &quot;Ottawa&quot;, 38]<br>]<br><br>print(tabulate(data, headers=headers))</pre><h4>2. Use headers=”firstrow”</h4><pre>from tabulate import tabulate<br><br>data = [<br>    [&quot;Country&quot;, &quot;Capital&quot;, &quot;Population (M)&quot;],<br>    [&quot;France&quot;, &quot;Paris&quot;, 67],<br>    [&quot;Japan&quot;, &quot;Tokyo&quot;, 126],<br>    [&quot;Canada&quot;, &quot;Ottawa&quot;, 38]<br>]<br><br>print(tabulate(data, headers=&quot;firstrow&quot;))</pre><h4>3. Use headers=”keys”</h4><pre>from tabulate import tabulate<br><br>data = {<br>    &quot;Country&quot;: [&quot;France&quot;, &quot;Japan&quot;, &quot;Canada&quot;],<br>    &quot;Capital&quot;: [&quot;Paris&quot;, &quot;Tokyo&quot;, &quot;Ottawa&quot;],<br>    &quot;Population (M)&quot;: [67, 126, 38]<br>}<br><br>print(tabulate(data, headers=&quot;keys&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*luto3mYa1JQ2Z6eFIimtrw.png" /><figcaption>Basic Table with Headers</figcaption></figure><h3>Row Indices</h3><p>showindex controls if (and how) an index column is added to your table. Here’s the base code we’ll reuse:</p><pre>from tabulate import tabulate<br><br>headers = [&quot;Book Title&quot;, &quot;Author&quot;]<br><br>data = [<br>    [&quot;Atomic Habits&quot;, &quot;James Clear&quot;],<br>    [&quot;Deep Work&quot;, &quot;Cal Newport&quot;],<br>    [&quot;The Alchemist&quot;, &quot;Paulo Coelho&quot;],<br>    [&quot;Sapiens&quot;, &quot;Yuval Noah Harari&quot;],<br>    [&quot;Python Crash Course&quot;, &quot;Eric Matthes&quot;]<br>]<br><br>print(tabulate(data, headers=headers, showindex=[YOUR_CHOICE_HERE]))</pre><h4>1. Index should be present</h4><ul><li>showindex=&quot;always&quot;</li><li>showindex=True</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*oVRO4L8HyXKnAN1pqzoOBQ.png" /><figcaption>Row indices are present</figcaption></figure><h4>2. No Index</h4><ul><li>showindex=&quot;never&quot;</li><li>showindex=False</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*vTbO-kPeEY-o_i8owMG-Rg.png" /><figcaption>No row indices are present</figcaption></figure><h4>3. Custom Index</h4><p>showindex is used to add custom index labels by passing list or any iterable.</p><pre>rowIndex = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;]<br>print(tabulate(data, headers=headers, showindex=rowIndex))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*scablU4jAz47j0chro04gA.png" /><figcaption>Custom Row Indices</figcaption></figure><h3>Numeric Column Alignment</h3><p>numalign is used to control numeric column alignment. Here’s the base code we’ll reuse:</p><pre>from tabulate import tabulate<br><br>headers = [&quot;Food Item&quot;, &quot;Quantity&quot;, &quot;Price&quot;]<br><br>data = [<br>    [&quot;Pizza&quot;, 2, 8.50],<br>    [&quot;Burger&quot;, 1, 5.00],<br>    [&quot;Sushi&quot;, 3, 12.00],<br>    [&quot;Pasta&quot;, 2, 7.25],<br>    [&quot;Salad&quot;, 1, 4.50]<br>]<br><br>print(tabulate(data, headers=headers, numalign=[YOUR_ALIGNMENT_OPTION_HERE]))</pre><ol><li>numalign=&quot;left&quot; → Left Alignment</li><li>numalign=&quot;right&quot; → Right Alignment</li><li>numalign=&quot;center&quot; → Center Alignment</li><li>numalign=&quot;decimal&quot; → Decimal Alignment (Aligned by decimal point)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*eTfzxSD5g1ELOeMPLe-P7A.png" /><figcaption>Numeric Column Alignment</figcaption></figure><h3>Text Alignment</h3><p>stralign is used to control text column alignment. Here’s the base code we’ll reuse:</p><pre>from tabulate import tabulate<br><br>headers = [&quot;Movie&quot;, &quot;Genre&quot;]<br><br>data = [<br>    [&quot;Inception&quot;, &quot;Sci-Fi&quot;],<br>    [&quot;The Dark Knight&quot;, &quot;Action&quot;],<br>    [&quot;Interstellar&quot;, &quot;Adventure&quot;],<br>    [&quot;Parasite&quot;, &quot;Thriller&quot;],<br>    [&quot;Coco&quot;, &quot;Animation&quot;]<br>]</pre><ol><li>stralign=&quot;left&quot; → Left Alignment</li><li>stralign=&quot;center&quot; → Center Alignment</li><li>stralign=&quot;right&quot; → Right Alignment</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*daQC-6T9ERCnAwZ2zgyaGQ.png" /><figcaption>Text Alignment</figcaption></figure><h3>Custom Column Alignment</h3><p>Use colalign to align each column individually.</p><p>Example:</p><ul><li>Team → left</li><li>Matches → center</li><li>Wins → right</li><li>Losses → right</li><li>Win % → decimal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*rmgWUa8ucu2FM5-mi3aU8Q.png" /><figcaption>Custom Column Alignment</figcaption></figure><h3>Float Formatting</h3><p>floatfmt controls decimal formatting in your tables.</p><pre>from tabulate import tabulate<br><br>headers = [&quot;Quarter&quot;, &quot;Revenue ($M)&quot;, &quot;Expenses ($M)&quot;, &quot;Profit ($M)&quot;]<br><br>data = [<br>    [&quot;Q1&quot;, 125.567, 100.234, 25.333],<br>    [&quot;Q2&quot;, 150.899, 120.5, 30.399],<br>    [&quot;Q3&quot;, 175.75, 130.875, 44.875],<br>    [&quot;Q4&quot;, 200.125, 145.667, 54.458]<br>]<br><br>print(tabulate(data, headers=headers, floatfmt=&quot;.2f&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*gzj5FhhOXYE1Cqolur1YcQ.png" /><figcaption>Format all floats to 2 decimal places</figcaption></figure><h4>Custom Float Formatting</h4><ul><li>Revenue → 2 decimal places</li><li>Expenses → 1 decimal place</li><li>Profit → 3 decimal places</li></ul><pre>from tabulate import tabulate<br><br>headers = [&quot;Quarter&quot;, &quot;Revenue ($M)&quot;, &quot;Expenses ($M)&quot;, &quot;Profit ($M)&quot;]<br><br>data = [<br>    [&quot;Q1&quot;, 125.567, 100.234, 25.333],<br>    [&quot;Q2&quot;, 150.899, 120.5, 30.399],<br>    [&quot;Q3&quot;, 175.75, 130.875, 44.875],<br>    [&quot;Q4&quot;, 200.125, 145.667, 54.458]<br>]<br><br>print(tabulate(data, headers=headers, floatfmt=(&quot;s&quot;, &quot;.2f&quot;, &quot;.1f&quot;, &quot;.3f&quot;)))</pre><p>(Here, &quot;s&quot; means <em>string column — no formatting</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*Gj3M6nTjGBtxVDEQcbt2qw.png" /><figcaption>Custom Float Formatting</figcaption></figure><h3>Integer Formatting</h3><p>intfmt is used to format integer values in your tables. Here’s the base code we’ll reuse:</p><pre>from tabulate import tabulate<br><br>headers = [&quot;Country&quot;, &quot;Population&quot;, &quot;GDP&quot;]<br><br>data = [<br>    [&quot;USA&quot;, 331002651, 21.43],<br>    [&quot;India&quot;, 1380004385, 2.87],<br>    [&quot;China&quot;, 1439323776, 14.34],<br>    [&quot;Brazil&quot;, 212559417, 1.84],<br>    [&quot;UK&quot;, 67886011, 2.83]<br>]</pre><ol><li>intfmt=&quot;left&quot; → adds thousands separators.</li><li>intfmt=&quot;_&quot; → uses underscores instead of commas (1_000_000)</li><li>intfmt=&quot;0nd&quot; → zero-padded. Padding will be added with 0 (e.g., intfmt=&quot;05d&quot; = 00042)</li><li>intfmt=&quot;d&quot; → default (plain integer)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*U7f1Ww-_RlOFjyIC_5dWBQ.png" /><figcaption>Integer Formatting</figcaption></figure><h3>Table Formatting</h3><p>tablefmt is used to format tables. Here’s the base code we’ll reuse:</p><pre>from tabulate import tabulate<br><br>data = [<br>    [&quot;Math&quot;, 95, &quot;A&quot;],<br>    [&quot;Science&quot;, 88, &quot;B+&quot;],<br>    [&quot;History&quot;, 76, &quot;C&quot;]<br>]<br><br>headers = [&quot;Subject&quot;, &quot;Score&quot;, &quot;Grade&quot;]<br><br>print(tabulate(data, headers, tablefmt=[YOUR_FORMAT_NAME_HERE]))</pre><ol><li>tablefmt=&quot;plain&quot;</li><li>tablefmt=&quot;simple&quot;</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*l6jaWOQA5Q_b0WOAouqb2Q.png" /><figcaption>Plain &amp; Simple Tables</figcaption></figure><p>3. tablefmt=&quot;grid&quot;</p><p>4. tablefmt=&quot;outline&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*A6PNMl8szI5y_44-_2ZAvw.png" /><figcaption>Outline format is similar to grid but without lines between rows.</figcaption></figure><p>5. tablefmt=&quot;simple_grid&quot;</p><p>6. tablefmt=&quot;simple_outline&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*EUZ-C-5ny2-1DeXPyOOKJQ.png" /><figcaption>Simple Outline format is similar to Simple grid but without lines between rows.</figcaption></figure><p>7. tablefmt=&quot;rounded_grid&quot;</p><p>8. tablefmt=&quot;rounded_outline&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*samm5p-hhxZpN3mKjXCzWg.png" /><figcaption>Rounded Outline format is similar to Rounded grid but without lines between rows.</figcaption></figure><p>9. tablefmt=&quot;heavy_grid&quot;</p><p>10. tablefmt=&quot;heavy_outline&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*fEIV4M4_xK4zaNyUX-U6dQ.png" /><figcaption>Heavy Outline format is similar to Heavy grid but without lines between rows.</figcaption></figure><p>11. tablefmt=&quot;mixed_grid&quot;</p><p>12. tablefmt=&quot;mixed_outline&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*YRTDwq6H_Xm08FcnEiicBA.png" /><figcaption>Mixed Outline format is similar to Mixed grid but without lines between rows.</figcaption></figure><p>13. tablefmt=&quot;double_grid&quot;</p><p>14. tablefmt=&quot;double_outline&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*1BE0Q62bkVX-Ync-Q5q4pg.png" /><figcaption>Double Outline format is similar to Double grid but without lines between rows.</figcaption></figure><p>15. tablefmt=&quot;fancy_grid&quot;</p><p>16. tablefmt=&quot;fancy_outline&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*7K-W7NMG8OxLfFOelrtEBQ.png" /><figcaption>Fancy Outline format is similar to Fancy grid but without lines between rows.</figcaption></figure><p>17. tablefmt=&quot;github&quot;</p><p>18. tablefmt=&quot;jira&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*8BxKuQsnoGRh96bF6gKrpA.png" /><figcaption>GitHub &amp; Jira Tables</figcaption></figure><p>19.tablefmt=&quot;mediawiki&quot;</p><p>20. tablefmt=&quot;html&quot;</p><p>21. tablefmt=&quot;latex&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMAb-Pua4-Dm7cD3BJjwVg.png" /><figcaption>Wikipedia, HTML &amp; Latex tables</figcaption></figure><p>22.tablefmt=&quot;presto&quot;</p><p>23. tablefmt=&quot;psql&quot;</p><p>24. tablefmt=&quot;pipe&quot;</p><p>25. tablefmt=&quot;asciidoc&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*_R_JdKcwg-OcJfDDKQBeCA.png" /><figcaption>Presto CLI, PostgreSQL, Pipe, Asciidoc Tables</figcaption></figure><h3>Preserving Whitespace</h3><p>By default, tabulate trims leading and trailing spaces from text columns. To preserve the whitespace we usePRESERVE_WHITESPACE.</p><h4>1. Default Behaviour</h4><pre>import tabulate<br><br>headers = [&quot;Text&quot;, &quot;Meaning&quot;]<br><br>data = [<br>    [&quot;   Indented&quot;, &quot;Has leading spaces&quot;],<br>    [&quot;Trimmed   &quot;, &quot;Has trailing spaces&quot;],<br>    [&quot;  Both  &quot;, &quot;Has leading + trailing spaces&quot;]<br>]<br><br>print(tabulate.tabulate(data, headers=headers))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*uaoPowsz20G6LxY_l6NDhA.png" /><figcaption>Whitespaces are trimmed</figcaption></figure><h4>2. Preserve whitespace</h4><pre>tabulate.PRESERVE_WHITESPACE = True<br>print(tabulate.tabulate(data, headers=headers))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*Pqntqes7gay8d6S2TXOhjg.png" /><figcaption>Preserve whitespace</figcaption></figure><h3>Bonus 1: Expense Tracker</h3><pre>from tabulate import tabulate<br><br>expenses = [<br>    [&quot;Laptop&quot;, &quot;Electronics&quot;, 1200.50],<br>    [&quot;Pizza&quot;, &quot;Food&quot;, 15.75],<br>    [&quot;Gas&quot;, &quot;Transport&quot;, 45.20],<br>    [&quot;Concert&quot;, &quot;Entertainment&quot;, 120.00],<br>    [&quot;Groceries&quot;, &quot;Food&quot;, 95.30],<br>]<br><br>headers = [&quot;Item&quot;, &quot;Category&quot;, &quot;Amount (INR)&quot;]<br><br>total = [[&quot;TOTAL&quot;, &quot;&quot;, sum(item[2] for item in expenses)]]<br><br>table = tabulate(expenses + total, headers, tablefmt=&quot;fancy_grid&quot;, floatfmt=&quot;.2f&quot;)<br><br>print(table)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*5-nGUEhb9bdwZycYaX6HcQ.png" /><figcaption>Expense Tracker</figcaption></figure><h3>Bonus 2: Task Tracker</h3><pre>from tabulate import tabulate<br><br>tasks = [<br>    [&quot;Finish report&quot;, &quot;High&quot;, &quot;2025-10-10&quot;],<br>    [&quot;Team meeting&quot;, &quot;Medium&quot;, &quot;2025-10-07&quot;],<br>    [&quot;Email client&quot;, &quot;Low&quot;, &quot;2025-10-06&quot;],<br>    [&quot;Update website&quot;, &quot;High&quot;, &quot;2025-10-12&quot;],<br>    [&quot;Backup files&quot;, &quot;Medium&quot;, &quot;2025-10-08&quot;],<br>]<br><br>headers = [&quot;Task&quot;, &quot;Priority&quot;, &quot;Deadline&quot;]<br><br>priority_count = [<br>    [&quot;High&quot;, sum(1 for t in tasks if t[1] == &quot;High&quot;)],<br>    [&quot;Medium&quot;, sum(1 for t in tasks if t[1] == &quot;Medium&quot;)],<br>    [&quot;Low&quot;, sum(1 for t in tasks if t[1] == &quot;Low&quot;)],<br>]<br><br>task_table = tabulate(tasks, headers, tablefmt=&quot;fancy_grid&quot;)<br>summary_table = tabulate(priority_count, headers=[&quot;Priority&quot;, &quot;Count&quot;], tablefmt=&quot;grid&quot;)<br><br>print(&quot;=== TASKS ===&quot;)<br>print(task_table)<br>print(&quot;\n=== PRIORITY SUMMARY ===&quot;)<br>print(summary_table)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*6e726vixHRrFDyfVC3JemA.png" /><figcaption>Task Tracker</figcaption></figure><h3><strong>Conclusion</strong></h3><p>Tabulate brings structure and style to your terminal output with almost no effort. It’s simple, fast, and perfect for anyone who wants clean, readable tables without extra dependencies.</p><p>Stay tuned for the next library drop in this series!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50f70a75862c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to Python Barcodes: 7 Formats and 4 Hands-On Projects]]></title>
            <link>https://medium.com/@jainsnehasj6/a-practical-guide-to-python-barcodes-7-formats-and-4-hands-on-projects-c81bd5547445?source=rss-ba78657f0862------2</link>
            <guid isPermaLink="false">https://medium.com/p/c81bd5547445</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[barcode]]></category>
            <category><![CDATA[python-libraries]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sneha Jain]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 13:38:54 GMT</pubDate>
            <atom:updated>2025-10-06T17:39:46.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-8p_N08jGmC4aY8H" /></figure><p>Barcodes are everywhere — from grocery stores to shipping labels — and generating them can be done directly in Python. The <strong>python-barcode</strong> library makes it simple to create barcodes for product labels, library IDs, or just to explore barcode technology. This guide shows how to generate barcodes quickly and efficiently, with minimal setup.</p><h3>Setting Up a Virtual Environment</h3><p>Keeping your dependencies isolated is essential for any Python project. Here’s a quick guide to creating and using a venv:</p><ol><li>Create the venv</li></ol><pre>python -m venv venv</pre><p>This creates a new folder named venv containing a clean Python environment.</p><p>2. Activate the venv</p><ul><li>Windows</li></ul><pre>venv\Scripts\activate</pre><ul><li>macOS/Linux</li></ul><pre>source venv/bin/activate</pre><h3>Installing Library</h3><pre>pip install python-barcode</pre><p>To output barcodes as PNG images, install the Pillow writer:</p><pre>pip install pillow</pre><h3>Supported Barcode Formats</h3><pre>import barcode<br>print(barcode.PROVIDED_BARCODES)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*844eWNjudkKEciuB.png" /><figcaption>Supported Barcode Formats</figcaption></figure><p>Common formats:</p><ul><li><strong>EAN‑8</strong>, <strong>EAN‑13</strong>: retail products</li><li><strong>UPC</strong>: US retail</li><li><strong>ISBN‑10</strong>, <strong>ISBN‑13</strong>: books</li><li><strong>ISSN</strong>: periodicals</li><li><strong>JAN</strong>: Japanese Article Number (variation of EAN)</li><li><strong>Code 39</strong>, <strong>Code 128</strong>, <strong>ITF</strong>: logistics, asset tracking</li></ul><h3>Generating an EAN‑13 Barcode (In SVG Format)</h3><pre>from barcode import EAN13<br>number = &#39;590123412345&#39;<br>my_code = EAN13(number)<br>my_code.save(&quot;barcode-1&quot;)</pre><h4>Steps:</h4><ol><li>Import <strong>EAN13</strong> from barcode.</li><li>Provide a <strong>12-digit string</strong> (library auto-adds the 13th checksum).</li><li>Create an <strong>EAN13 object</strong> with the number.</li><li>Save barcode as <strong>.svg</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/0*civcmBP_C11R-i7t.png" /><figcaption>EAN13 Barcode</figcaption></figure><h3>Generating an EAN‑13 Barcode (In PNG Format)</h3><pre>from barcode import EAN13<br>from barcode.writer import ImageWriter<br>number = &#39;590123412345&#39;<br>my_code = EAN13(number, writer=ImageWriter())<br>my_code.save(&quot;barcode-1&quot;)</pre><h3>Steps:</h3><ol><li>Import <strong>EAN13</strong> and <strong>ImageWriter</strong>.</li><li>Provide a <strong>12-digit string</strong> (library auto-adds the 13th checksum).</li><li>Create <strong>EAN13(number, ImageWriter())</strong>.</li><li>Save as <strong>.png</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*Mui6lgDa42VRX-Sy.png" /><figcaption>EAN‑13 Barcode in PNG format</figcaption></figure><h3>Generating an EAN‑8 Barcode</h3><pre>from barcode import EAN8<br>from barcode.writer import ImageWriter<br>number = &#39;1234567&#39;<br>my_code = EAN8(number, writer=ImageWriter())<br>my_code.save(&quot;barcode-2&quot;)</pre><p>Use a 7-digit string (library auto-adds the 8th checksum).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/0*rWbm_yz4Cjb347of.png" /><figcaption>EAN8 Barcode</figcaption></figure><h3>Generating an ISBN‑13 Barcode</h3><pre>from barcode import ISBN13<br>from barcode.writer import ImageWriter<br>number = &#39;978316148410&#39;<br>my_code = ISBN13(number, writer=ImageWriter())<br>my_code.save(&quot;isbn13-barcode&quot;)</pre><p>A <strong>12-digit string</strong> (library auto-adds the 13th checksum).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*4B-nau-_coNHGf-Y.png" /><figcaption>ISBN13 Barcode</figcaption></figure><h3>Generating an UPC‑A Barcode</h3><pre>from barcode import UPCA<br>from barcode.writer import ImageWriter<br>number = &#39;12345678901&#39;<br>my_code = UPCA(number, writer=ImageWriter())<br>my_code.save(&quot;upca-barcode&quot;)</pre><p>A <strong>11-digit string</strong> (library auto-adds the 12th checksum).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*HYBptnhqP84TsrmF.png" /><figcaption>UPC‑A Barcode</figcaption></figure><h3>Generating an Code 39 Barcode</h3><pre>from barcode import Code39<br>from barcode.writer import ImageWriter<br>my_code = Code39(&#39;ABC-1234&#39;, writer=ImageWriter(), add_checksum=False)<br>my_code.save(&quot;code39-barcode&quot;)</pre><p>add_checksum = False means that it is not going to add checksum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*o8vpFypNtWPx_NHr.png" /><figcaption>Code 39 Barcode</figcaption></figure><h3>Generating an Code 128 Barcode</h3><pre>from barcode import Code128<br>from barcode.writer import ImageWriter<br>my_code = Code128(&#39;HELLO-1234-567&#39;, writer=ImageWriter())<br>my_code.save(&quot;code128-barcode&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*6a1QBNUd_poF7DqS.png" /><figcaption>Code 128 Barcode</figcaption></figure><h3>Generating an ISSN Barcode</h3><pre>from barcode import ISSN <br>from barcode.writer import ImageWriter<br>number = &#39;1234567&#39;<br>my_code = ISSN (number, writer=ImageWriter())<br>my_code.save(&quot;issn-barcode&quot;)</pre><p>The number is prefixed by 977 and a checksum is added at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*0-wkRdmk-CQaC-UD.png" /><figcaption>ISSN Barcode</figcaption></figure><h3>Bonus 1: Generate Barcode In-Memory (No Files!)</h3><pre>import io<br>from PIL import Image<br>import barcode<br>from barcode.writer import ImageWriter<br><br>fp = io.BytesIO()<br>code = barcode.get(&#39;code128&#39;, &#39;INMEMORY123&#39;, writer=ImageWriter())<br>code.write(fp)<br><br>fp.seek(0)<br>img = Image.open(fp)<br>img.show()<br>Press enter or click to view image in full size</pre><ul><li>io.BytesIO() → creates an in-memory file-like object.</li><li>barcode.get(&#39;code128&#39;, &#39;INMEMORY123&#39;, writer=ImageWriter()) → generates a <strong>Code128 barcode</strong> from the string &quot;INMEMORY123&quot;, output as an image.</li><li>code.write(fp) → writes the barcode image into the in-memory file.</li><li>fp.seek(0) → resets pointer to the beginning of the in-memory file.</li><li>Image.open(fp) → loads the image with Pillow.</li><li>img.show() → opens the generated barcode image in the default image viewer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*6iLIjP166DxBEsaJ.png" /><figcaption>Barcode In-Memory</figcaption></figure><h3>Bonus 2: Bulk Barcode Generator for Journals</h3><pre>import os<br>from barcode import ISSN<br>from barcode.writer import ImageWriter<br><br>issns = {<br>    &quot;AI Research Monthly&quot;: &quot;2049363&quot;,<br>    &quot;Medical Today&quot;: &quot;1234567&quot;,<br>    &quot;Data Journal&quot;: &quot;9876543&quot;,<br>    &quot;Global Tech Review&quot;: &quot;3344556&quot;,<br>    &quot;Neuroscience Weekly&quot;: &quot;5566778&quot;,<br>    &quot;Climate &amp; Environment&quot;: &quot;7788990&quot;,<br>    &quot;Journal of Machine Learning&quot;: &quot;1112233&quot;,<br>    &quot;Quantum Physics Digest&quot;: &quot;4445566&quot;,<br>    &quot;Bioinformatics Letters&quot;: &quot;6677889&quot;,<br>    &quot;Historical Archives&quot;: &quot;9990001&quot;<br>}<br><br>output_dir = &quot;journal_barcodes&quot;<br>os.makedirs(output_dir, exist_ok=True)<br><br>for journal, issn in issns.items():<br>    barcode = ISSN(issn, writer=ImageWriter())<br>    filename = os.path.join(output_dir, journal.replace(&quot; &quot;, &quot;_&quot;))<br>    barcode.save(filename)<br>    print(f&quot;Saved barcode for {journal}&quot;)</pre><ul><li><strong>output_dir</strong> → creates a folder journal_barcodes to store the barcodes.</li><li>The loop goes through each journal name and its ISSN.</li><li>Generate an <strong>ISSN barcode</strong> (ISSN(issn, writer=ImageWriter())).</li><li>Save it as an image (.png) with the journal name as the filename (spaces replaced by underscores).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*SfoPHqhr50W9MCzG.png" /><figcaption>Bulk Barcode Generation Output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*Oy1z_nvR-xKkmyun.png" /><figcaption>AI Research Monthly Barcode</figcaption></figure><h3>Bonus 3: Barcode Generator from CSV for Inventory Data</h3><h4>data.csv (For reference)</h4><pre>name,id<br>Treadmill,EQP-001<br>Dumbbells Set,EQP-002<br>Yoga Mat,EQP-003<br>Resistance Bands,EQP-004<br>Kettlebell,EQP-005<br>Exercise Bike,EQP-006<br>Foam Roller,EQP-007<br>Jump Rope,EQP-008<br>Pull-Up Bar,EQP-009<br>Ab Wheel,EQP-010<br>Rowing Machine,EQP-011<br>Balance Ball,EQP-012<br>Ankle Weights,EQP-013<br>Punching Bag,EQP-014<br>Speed Ladder,EQP-015</pre><pre>import csv<br>import os<br>from barcode import Code128<br>from barcode.writer import ImageWriter<br><br>csv_file = &#39;data.csv&#39;<br>output_dir = &#39;inventory_barcodes&#39;<br>os.makedirs(output_dir, exist_ok=True)<br><br>with open(csv_file, newline=&#39;&#39;, encoding=&#39;utf-8&#39;) as file:<br>    for row in csv.DictReader(file):<br>        item_name, item_id = row[&#39;name&#39;], row[&#39;id&#39;]<br><br>        code = Code128(item_id, writer=ImageWriter())<br>        filename = os.path.join(output_dir, item_name.replace(&quot; &quot;, &quot;_&quot;))<br>        code.save(filename)<br><br>        print(f&quot;Saved barcode for {item_name} (ID: {item_id})&quot;)</pre><ul><li><strong>output_dir</strong> → creates a folder inventory_barcodes to store the barcodes.</li><li>Opens the CSV file and reads name and id fields for each row.</li><li>Generate Code128 <strong>barcode</strong> (Code128(item_id, writer=ImageWriter())).</li><li>Saves it as an image (.png), with the file named after the item’s name (spaces replaced by underscores).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*9nes_QhvuQQvSE1H.png" /><figcaption>Barcode Generation from CSV for Gym Items</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*UGkT34LpCitW2Sw1.png" /><figcaption>Yoga Mat Barcode</figcaption></figure><h3>Bonus 4: Create Barcodes as a Single PDF for Library Books</h3><h4>books.csv (For Reference)</h4><pre>title,isbn<br>Python Crash Course,9781593276034<br>Fluent Python,9781491946008<br>Deep Learning with Python,9781617294433<br>Automate the Boring Stuff,9781593275990<br>Effective Python,9780134034287<br>Think Python,9781491939369<br>Python for Data Analysis,9781491957660<br>Python Cookbook,9781449340377<br>Hands-On Machine Learning with Scikit-Learn and TensorFlow,9781492032649<br>Natural Language Processing with Python,9780596516499<br>Programming Python,9781449359362<br>Learning Python,9781449355739<br>Python Data Science Handbook,9781491912058<br>Data Structures and Algorithms in Python,9781118290279</pre><pre>import os<br>import csv<br>from barcode import ISBN13<br>from barcode.writer import ImageWriter<br>from fpdf import FPDF<br><br>csv_file = &#39;books.csv&#39;<br>barcode_dir = &#39;isbn_images&#39;<br>output_pdf = &#39;books_barcodes.pdf&#39;<br><br>os.makedirs(barcode_dir, exist_ok=True)<br><br>pdf = FPDF()<br>pdf.add_page()<br>pdf.set_auto_page_break(auto=True, margin=15)<br>pdf.set_font(&quot;Arial&quot;, size=12)<br>y = 10  <br><br>with open(csv_file, newline=&#39;&#39;, encoding=&#39;utf-8&#39;) as f:<br>    for row in csv.DictReader(f):<br>        title, isbn = row[&#39;title&#39;], row[&#39;isbn&#39;]<br>        <br>        code = ISBN13(isbn, writer=ImageWriter())<br>        filename_base = os.path.join(barcode_dir, title.replace(&quot; &quot;, &quot;_&quot;))<br>        code.save(filename_base)<br><br>        pdf.set_xy(10, y)<br>        pdf.cell(0, 10, txt=f&quot;{title} - {isbn}&quot;, ln=True)<br>        y += 10<br>        image_path = filename_base + &quot;.png&quot;<br>        pdf.image(image_path, x=10, y=y, w=100, h=30)<br>        y += 40  <br><br>        if y &gt; 250:<br>            pdf.add_page()<br>            y = 10<br><br>pdf.output(output_pdf)<br>print(f&quot;PDF saved as &#39;{output_pdf}&#39;&quot;)</pre><ul><li>barcode_dir → creates a folder isbn_images to store the barcodes.</li><li>Initializes a PDF with one page, sets font and auto page break, and defines starting y-position for content.</li><li>Opens the CSV file and reads title and isbn fields for each row.</li><li>Generate ISBN13 <strong>barcode</strong> (ISBN13(isbn, writer=ImageWriter())).</li><li>Adds title and ISBN text, places barcode below it, and updates y for the next entry.</li><li>If y goes beyond the page height (~297 mm for A4), start a new page and reset y.</li><li>Saves the generated PDF with all the barcodes and prints confirmation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*JiFy5LrjymxX2YsE.png" /><figcaption>Barcode Generation Images</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*FOxteeHb7H0AH0DY.png" /><figcaption>PDF of Barcodes</figcaption></figure><h3>Conclusion</h3><p>python-barcode makes it simple to generate barcodes in Python — whether you&#39;re saving them as images, displaying them in memory, or using them in PDFs and web apps. It&#39;s beginner-friendly, supports popular barcode formats, and works well for automation and bulk generation tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c81bd5547445" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>