<?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 Saurabh Gandhi on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Gandhi on Medium]]></description>
        <link>https://medium.com/@sams.article?source=rss-a731cc558870------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Eq5iwkX87s90K7J2VkXFoQ.png</url>
            <title>Stories by Saurabh Gandhi on Medium</title>
            <link>https://medium.com/@sams.article?source=rss-a731cc558870------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:47:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sams.article/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[4 Pillars of Object-Oriented Programming (OOP)]]></title>
            <link>https://medium.com/@sams.article/4-pillars-of-object-oriented-programming-oop-19d5ada7196d?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d5ada7196d</guid>
            <category><![CDATA[oop-python]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[abstraction]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 04:55:25 GMT</pubDate>
            <atom:updated>2026-04-21T04:55:25.364Z</atom:updated>
            <content:encoded><![CDATA[<p>Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. These objects represent real-world entities and contain both data (attributes) and behavior (methods).</p><p>The foundation of OOP is built on four fundamental principles, often called the 4 Pillars of OOP:</p><ol><li>Encapsulation</li><li>Abstraction</li><li>Inheritance</li><li>Polymorphism</li></ol><p>These principles help developers write modular, reusable, scalable, and maintainable code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*c7yHdrGCEhdZSn8Ojz81gQ.png" /></figure><h3>1. Encapsulation</h3><p>Encapsulation is the concept of <strong>bundling data (variables) and methods (functions) together inside a class and restricting direct access to some of the object’s data</strong>.</p><p>In simple words:</p><blockquote><em>Encapsulation means </em><strong><em>protecting the internal state of an object and controlling how it is accessed or modified</em></strong><em>.</em></blockquote><h4>Real-Life Analogy</h4><p>Think of a <strong>bank account</strong>.</p><p>You cannot directly access or modify the balance.<br> Instead, you interact with it through methods like:</p><ul><li>deposit()</li><li>withdraw()</li><li>check_balance()</li></ul><p>The internal data (balance) is <strong>protected</strong>.</p><p><strong>Example:</strong></p><pre>class BankAccount:<br><br>    def __init__(self, balance):<br>        self.__balance = balance   # private variable<br><br>    def deposit(self, amount):<br>        self.__balance += amount<br><br>    def get_balance(self):<br>        return self.__balance<br><br><br>account = BankAccount(1000)<br><br>account.deposit(500)<br><br>print(account.get_balance())</pre><ul><li>__balance is <strong>encapsulated</strong></li><li>It cannot be accessed directly outside the class</li></ul><h3><strong>2. Abstraction</strong></h3><p>Abstraction means <strong>hiding complex implementation details and showing only the essential features of an object</strong>.</p><p>In simple words:</p><blockquote><em>The user interacts with </em><strong><em>what the object does</em></strong><em>, not </em><strong><em>how it does it</em></strong><em>.</em></blockquote><h4>Real-Life Analogy</h4><p>Consider a <strong>car</strong>.</p><p>You only interact with:</p><ul><li>steering wheel</li><li>accelerator</li><li>brake</li></ul><p>But you don’t see the <strong>complex engine mechanics</strong> behind it.</p><p>That complexity is <strong>abstracted away</strong>.</p><p><strong>Example:</strong></p><pre>class Car:<br><br>    def start(self):<br>        print(&quot;Car is starting...&quot;)<br><br><br>my_car = Car()<br>my_car.start()</pre><p>The user simply calls start().<br>The internal engine logic is hidden.</p><h3>3. Inheritance</h3><p>Inheritance allows a <strong>class to inherit properties and methods from another class</strong>.</p><p>In simple words:</p><blockquote><em>One class can reuse the code of another class.</em></blockquote><h4>Real-Life Analogy</h4><p>A <strong>Dog</strong> is an <strong>Animal</strong>.</p><p>So Dog automatically has common properties like:</p><ul><li>eat</li><li>sleep</li><li>breathe</li></ul><p>Dog can also have its <strong>own unique behavior</strong> like barking.</p><p><strong>Example:</strong></p><pre>class Animal:<br><br>    def eat(self):<br>        print(&quot;Animal is eating&quot;)<br><br><br>class Dog(Animal):<br><br>    def bark(self):<br>        print(&quot;Dog is barking&quot;)<br><br><br>d = Dog()<br><br>d.eat()<br>d.bark()</pre><p>Here:</p><ul><li>Dog <strong>inherits</strong> from Animal</li><li>Dog automatically gets the eat() method</li></ul><h3>4. Polymorphism</h3><p>Polymorphism means <strong>one interface, multiple implementations</strong>.</p><p>In simple words:</p><blockquote><em>The same method name can behave </em><strong><em>differently for different objects</em></strong><em>.</em></blockquote><h4>Real-Life Analogy</h4><p>The word <strong>“run”</strong> can mean different things:</p><ul><li>A <strong>person runs</strong></li><li>A <strong>car runs</strong></li><li>A <strong>program runs</strong></li></ul><p>Same word, different behavior.</p><p><strong>Example:</strong></p><pre>class Dog:<br>    def speak(self):<br>        print(&quot;Dog barks&quot;)<br><br><br>class Cat:<br>    def speak(self):<br>        print(&quot;Cat meows&quot;)<br><br><br>animals = [Dog(), Cat()]<br><br>for animal in animals:<br>    animal.speak()</pre><p>Here:</p><ul><li>Both classes use the same method speak()</li><li>But behavior is different</li></ul><h3>Summary of the 4 Pillars</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Hg1DSCf_pOHqA0m27eqq5A.png" /></figure><h4>Key Takeaway</h4><p>The <strong>4 pillars of OOP work together</strong> to make software:</p><ul><li>modular</li><li>reusable</li><li>scalable</li><li>easier to maintain</li></ul><p>Most modern frameworks and systems (like <strong>Django, TensorFlow, PyTorch, and large-scale enterprise applications</strong>) heavily rely on these OOP principles.</p><h3>Questions</h3><ol><li>What are the four pillars of Object-Oriented Programming?</li><li>What is Encapsulation in OOP?</li><li>What is Abstraction?</li><li>What is Inheritance?</li><li>What is Polymorphism?</li><li>Which pillar focuses on data hiding?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/object-oriented-programming-oop-in-python-7f1fe4bca89f">Object-Oriented Programming (OOP) in Python</a></li><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d5ada7196d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magic (Dunder) Methods in Python]]></title>
            <link>https://medium.com/@sams.article/magic-dunder-methods-in-python-ae4840d87845?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae4840d87845</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[methods]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[dunder-method]]></category>
            <category><![CDATA[python-magic-method]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 04:47:35 GMT</pubDate>
            <atom:updated>2026-04-15T04:47:35.823Z</atom:updated>
            <content:encoded><![CDATA[<p>In Python’s <strong>object-oriented model</strong>, objects can interact with built-in language features such as print(), len(), comparison operators, and more. This interaction is enabled through <strong>special methods</strong>, commonly called <strong>Magic Methods</strong> or <strong>Dunder Methods</strong> (Double-UNDERscore methods).</p><p>These methods allow developers to define how objects behave when used with Python’s built-in operations.</p><p>For example:</p><ul><li>print(obj) → calls __str__()</li><li>len(obj) → calls __len__()</li><li>obj1 == obj2 → calls __eq__()</li></ul><p>Magic methods make <strong>custom objects behave like built-in Python types</strong> such as lists, strings, or dictionaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*YRwHk4aehU31t3qaGZHbUQ.png" /></figure><h3>Understanding Magic (Dunder) Methods</h3><p>Magic methods are predefined method names in Python that begin and end with <strong>double underscores</strong>.</p><p><strong>Example:</strong></p><pre>__init__<br>__str__<br>__repr__<br>__len__<br>__eq__</pre><p>These methods are <strong>not meant to be called directly</strong>. Instead, Python automatically invokes them when certain operations occur.</p><p><strong>Example:</strong></p><pre>class Demo:<br>  def __str__(self):<br>    return &quot;Demo Object&quot;<br><br>d = Demo()<br>print(d)# internally becomes d.__str__()</pre><h3>Why Magic Methods Are Important</h3><p>Magic methods allow developers to:</p><ul><li>Customize object behavior</li><li>Integrate custom classes with Python’s built-in functions</li><li>Implement operator overloading</li><li>Build intuitive APIs</li><li>Make objects behave like built-in data types</li></ul><p>Without magic methods, custom classes would be much less flexible.</p><h3>1. __str__() — Human-Readable Representation</h3><p>__str__() returns a <strong>human-friendly string representation</strong> of an object.</p><p>This method is automatically called by:</p><ul><li>print(obj)</li><li>str(obj)</li><li>format(obj)</li></ul><p>The goal of __str__() is to provide a <strong>clean and readable description of the object</strong>.</p><p><strong>Syntax:</strong></p><pre>def __str__(self):<br>    return &quot;string representation&quot;</pre><p><strong>Example:</strong></p><pre>class Student:<br><br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>    def __str__(self):<br>        return f&quot;Student(Name={self.name}, Age={self.age})&quot;<br><br><br>s = Student(&quot;Alice&quot;, 22)<br>print(s)<br># output:<br>  # Student(Name=Alice, Age=22)</pre><p><strong>Without __str__()</strong></p><p>If __str__() is not implemented:</p><pre>print(s)<br># Output:<br>  # &lt;__main__.Student object at 0x0000018F2D3&gt;</pre><p>This output is not useful for users.</p><h3>2. __repr__() — Developer-Focused Representation</h3><p>__repr__() returns the <strong>official string representation of an object</strong> intended for developers and debugging.</p><p>It is used by:</p><ul><li>Python interpreter</li><li>Debugging tools</li><li>repr(obj)</li><li>Interactive shell</li></ul><p>The representation should ideally allow recreating the object.</p><p><strong>Syntax:</strong></p><pre>def __repr__(self):<br>    return &quot;representation&quot;</pre><p><strong>Example:</strong></p><pre>class Student:<br><br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>    def __repr__(self):<br>        return f&quot;Student(&#39;{self.name}&#39;, {self.age})&quot;<br><br>s = Student(&quot;Alice&quot;, 22)<br>repr(s)<br># output:<br>  # Student(&#39;Alice&#39;, 22)</pre><p><strong>__repr__() vs </strong><strong>__str__()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*NC2JpFgO8y1TjtLHXK_Duw.png" /></figure><p><strong>Example:</strong></p><pre>class Product:<br><br>    def __init__(self, name, price):<br>        self.name = name<br>        self.price = price<br><br>    def __str__(self):<br>        return f&quot;{self.name} costs ₹{self.price}&quot;<br><br>    def __repr__(self):<br>        return f&quot;Product(&#39;{self.name}&#39;, {self.price})&quot;<br><br><br>p = Product(&quot;Laptop&quot;, 75000)<br><br>print(p)<br>repr(p)</pre><h3>3. __len__() — Defining Object Length</h3><p>__len__() allows an object to define its <strong>length</strong>.</p><p>It is invoked when calling:</p><pre>len(object)</pre><p>This method must return a <strong>non-negative integer</strong>.</p><p><strong>Example:</strong></p><pre>class Library:<br><br>    def __init__(self, books):<br>        self.books = books<br><br>    def __len__(self):<br>        return len(self.books)<br><br><br>lib = Library([&quot;Python&quot;, &quot;ML&quot;, &quot;AI&quot;])<br><br>print(len(lib))</pre><p><strong>Practical Example — Shopping Cart</strong></p><pre>class ShoppingCart:<br><br>    def __init__(self):<br>        self.items = []<br><br>    def add_item(self, item):<br>        self.items.append(item)<br><br>    def __len__(self):<br>        return len(self.items)<br><br><br>cart = ShoppingCart()<br><br>cart.add_item(&quot;Laptop&quot;)<br>cart.add_item(&quot;Mouse&quot;)<br><br>print(len(cart))</pre><h3>4. __del__() — Object Destructor</h3><p>__del__() is a destructor method called when an object is about to be destroyed.</p><p>It is used for:</p><ul><li>releasing resources</li><li>closing files</li><li>cleaning up connections</li></ul><p><strong>Syntax:</strong></p><pre>def __del__(self):<br>    # cleanup code</pre><p><strong>Example:</strong></p><pre>class FileHandler:<br><br>    def __init__(self, filename):<br>        self.file = open(filename, &quot;w&quot;)<br><br>    def __del__(self):<br>        print(&quot;Closing file&quot;)<br>        self.file.close()<br><br><br>f = FileHandler(&quot;test.txt&quot;)<br>del f</pre><h4>Important Concept: Garbage Collection</h4><p>Python uses <strong>reference counting and garbage collection</strong> to destroy objects.</p><p>Therefore, __del__() execution time is <strong>not always predictable</strong>.</p><p>This means:</p><pre>__del__() is rarely used in production systems</pre><p>Instead developers use <strong>context managers (</strong><strong>with statement)</strong>.</p><h3>5. __eq__() — Custom Equality Comparison</h3><p>__eq__() defines how two objects should be compared using ==.</p><p><strong>Syntax:</strong></p><pre>def __eq__(self, other):</pre><p><strong>Example:</strong></p><pre>class Employee:<br><br>    def __init__(self, emp_id):<br>        self.emp_id = emp_id<br><br>    def __eq__(self, other):<br>        return self.emp_id == other.emp_id<br><br><br>e1 = Employee(101)<br>e2 = Employee(101)<br><br>print(e1 == e2)</pre><h4>Default Behavior Without __eq__</h4><p>Without defining __eq__, Python compares <strong>memory addresses</strong>.</p><p><strong>Example:</strong></p><pre>class Test:<br>    pass<br><br>a = Test()<br>b = Test()<br><br>print(a == b)</pre><h3>Execution Flow of Magic Methods</h3><pre>User Operation<br>      |<br>      v<br>Python Built-in Function<br>      |<br>      v<br>Magic Method Triggered</pre><p><strong>Example:</strong></p><pre>print(obj)      → obj.__str__()<br>repr(obj)       → obj.__repr__()<br>len(obj)        → obj.__len__()<br>del obj         → obj.__del__()<br>obj1 == obj2    → obj.__eq__()</pre><h3>Questions</h3><ol><li>What are magic methods in Python?</li><li>Why are they called “dunder methods”?</li><li>What is the purpose of __str__()?</li><li>Difference between __str__() and __repr__()?</li><li>When does Python call __len__()?</li><li>What happens if __eq__() is not implemented?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/object-oriented-programming-oop-in-python-7f1fe4bca89f">Object-Oriented Programming (OOP) in Python</a></li><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae4840d87845" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Class vs Instance Attributes]]></title>
            <link>https://medium.com/@sams.article/class-vs-instance-attributes-5fc68a0327a7?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fc68a0327a7</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 06:32:18 GMT</pubDate>
            <atom:updated>2026-04-09T06:32:18.505Z</atom:updated>
            <content:encoded><![CDATA[<p>Object-Oriented Programming (OOP) in Python revolves around classes and objects. One of the most important concepts in class design is understanding the difference between Class Attributes and Instance Attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*5cNFwIWE60SmqsRf2A23SQ.png" /></figure><h3>What are Class Variables?</h3><ul><li>Class Variables are variables that are shared by all objects (instances) of a class.</li><li>They belong to the class itself, not to individual objects.</li><li>All objects access the same memory location for class variables.</li></ul><h4><strong>Simple Definition</strong></h4><blockquote>A class variable is defined inside the class but outside all methods, and it is shared by every instance of the class.</blockquote><h4><strong>Syntax</strong></h4><pre>class ClassName:<br>  class_variable = value</pre><h4>Example</h4><pre>class Compnay:<br>  company_name = &quot;ABC&quot;<br><br># here,<br>  # company_name is a class variable</pre><h4>Example of Class Variables</h4><pre>class Employee:<br>  compnay = &quot;ABC PVT. LID.&quot;<br>  <br>  def __init__(self,name, salary):<br>    self.name = name<br>    self.salary = salary<br><br>emp_1 = Employee(&quot;Rahul&quot;,25000)<br>emp_1 = Employee(&quot;Priya&quot;,15000)<br><br><br>print(emp1.company)<br>print(emp2.company)<br><br># output: <br>  # ABC PVT. LID.<br>  # ABC PVT. LID.<br><br># here,<br>  # Both emp1 and emp2 share the same company variable.</pre><h4>Memory Structure of Class Variables</h4><pre>Class (Employee)<br>│<br>├── company = &quot;ABC PVT. LID.&quot;<br>│<br>├── Object emp1<br>│     ├── name = Rahul<br>│     └── salary = 25000<br>│<br>└── Object emp2<br>      ├── name = Priya<br>      └── salary = 15000</pre><blockquote>company variable is stored once in class memory</blockquote><p>All objects refer to it.</p><h4>Accessing Class Variables</h4><p>There are two ways.</p><h4>1. Using Class Name (Recommended)</h4><pre>print(Employee.company)</pre><h4>2. Using Object</h4><pre>print(emp1.company)</pre><h4>Modifying Class Variables</h4><p>Class variables can be changed in two ways.</p><h4>1. Modify using Class Name</h4><pre>class Employee:<br>  company = &quot;ABC PVT. LID.&quot;<br><br>Employee.company = &quot;CDE PVT. LID.&quot;<br>print(Employee.company)</pre><h4>2. Modify using Object</h4><pre>emp1.company = &quot;Amazon&quot;</pre><p>Important:</p><ul><li>This <strong>does not modify the class variable</strong>.</li><li>Instead it <strong>creates a new instance variable</strong> for that object.</li></ul><h4>Example:</h4><pre>class Employee:<br>  company = &quot;ABC&quot;<br><br>emp1 = Employee()<br>emp2 = Employee()<br><br>emp1.company = &quot;DEF&quot;<br>print(emp1.company)<br>print(emp2.company)<br><br># output:<br>  # ABC<br>  # DEF</pre><h3>What are Instance Variables?</h3><p>Instance variables are variables that belong to individual objects (instances) of a class.</p><p>Each object gets its own copy of these variables.</p><h4>Simple Definition</h4><blockquote>Instance variables are variables defined inside a method (usually __init__) using self and they store data specific to each object.</blockquote><h4>Syntax</h4><pre>class ClassName:<br>    <br>    def __init__(self):<br>        self.variable_name = value</pre><h4>Example:</h4><pre>class Student:<br><br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br># here,<br>  # self.name<br>  # self.age<br># are instance variables.</pre><h4>Example</h4><pre>class Employee:<br><br>    def __init__(self, name, salary):<br>        self.name = name<br>        self.salary = salary<br><br><br>emp1 = Employee(&quot;Rahul&quot;, 50000)<br>emp2 = Employee(&quot;Priya&quot;, 70000)<br><br>print(emp1.name, emp1.salary)<br>print(emp2.name, emp2.salary)</pre><h4>Memory Structure of Instance Variables</h4><pre>Class: Employee<br>│<br>├── Object emp1<br>│     ├── name = Rahul<br>│     └── salary = 50000<br>│<br>└── Object emp2<br>      ├── name = Priya<br>      └── salary = 70000</pre><p>Instance variables are stored separately for each object</p><h4>Where Can Instance Variables Be Created?</h4><p>Instance variables can be created in three places.</p><h4>1. Inside Constructor (__init__)</h4><pre>class Student:<br><br>    def __init__(self, name):<br>        self.name = name</pre><h4>2. Inside Instance Methods</h4><pre>class Student:<br><br>    def set_age(self, age):<br>        self.age = age</pre><h4>3. Outside the Class (Using Object)</h4><pre>class Student:<br>    pass<br><br>s1 = Student()<br>s1.name = &quot;Rahul&quot;</pre><h4>Accessing Instance Variables</h4><p>Instance variables are accessed using <strong>object reference</strong>.</p><pre>class Car:<br><br>    def __init__(self, brand):<br>        self.brand = brand<br><br><br>c1 = Car(&quot;BMW&quot;)<br><br>print(c1.brand)</pre><h4>Modifying Instance Variables</h4><p>Instance variables can be modified easily.</p><pre>class Student:<br><br>    def __init__(self, name):<br>        self.name = name<br><br><br>s1 = Student(&quot;Rahul&quot;)<br><br>s1.name = &quot;Amit&quot;<br><br>print(s1.name)</pre><h4>Deleting Instance Variables</h4><p>You can delete them using del.</p><pre>class Student:<br><br>    def __init__(self, name):<br>        self.name = name<br><br><br>s1 = Student(&quot;Rahul&quot;)<br><br>del s1.name</pre><h3>Questions</h3><ol><li>What is a Class Variable in Python?</li><li>What is an Instance Variable?</li><li>How do you access a class variable?</li><li>How do you create a class in Python?</li><li>How do you access an instance variable?</li><li>How many copies of class variables exist?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li><li><a href="https://medium.com/@sams.article/object-oriented-programming-oop-in-python-7f1fe4bca89f">Object-Oriented Programming (OOP) in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fc68a0327a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classes and Objects in Python]]></title>
            <link>https://medium.com/@sams.article/classes-and-objects-in-python-4119939735fe?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/4119939735fe</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop-python]]></category>
            <category><![CDATA[classes-and-objects]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 05:50:03 GMT</pubDate>
            <atom:updated>2026-04-06T05:50:03.825Z</atom:updated>
            <content:encoded><![CDATA[<p>Object-Oriented Programming (OOP) is one of the most powerful paradigms in Python.<br>If you want to build scalable applications, crack interviews, or understand frameworks like Django deeply, mastering these fundamentals is non-negotiable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*tZ9ehezKrVCPZTF6p9z6dA.png" /></figure><h3>Class</h3><p>A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type.</p><blockquote>A <strong>class</strong> is a blueprint for creating objects.</blockquote><p><strong>Syntax:</strong></p><pre>class ClassName:<br>  pass</pre><p><strong>Example:</strong></p><pre>class Person:<br>  pass</pre><p>Here:</p><ul><li>class is the keyword.</li><li>Person is the class name (by convention, class names use PascalCase).</li><li>pass means “do nothing for now.”</li></ul><p>At this stage, the class doesn’t store any data or perform any action. It’s just a structure.</p><h4>Creating Class</h4><p>Classes are created using <strong>class keyword</strong>. Attributes are variables defined inside class and represent properties of the class. Attributes can be accessed using dot<strong> . operator</strong></p><h3>Object</h3><p>An <strong>object</strong> is a specific instance of a class. It holds its own set of data (instance variables) and can invoke methods defined by its class. Multiple objects can be created from same class, each with its own unique attributes.</p><p><strong>Example:</strong></p><pre>class Person:<br>  pass<br><br>p1 = Person() # Creating object from class</pre><p>Here:</p><ul><li>p1 is an object.</li><li>Person() calls the class to create a new instance.</li></ul><p>You can create the multiple objects:</p><pre>p2 = Person()<br>p3 = Person()</pre><p>Each object is independent.</p><h3>The __init__() Constructor</h3><p>The __init__() method acts as a constructor in Python and is automatically executed when an object is created. It is used to initialize the attributes of the object with the values provided at the time of object creation.</p><p><strong>Why Do We Need It?</strong></p><ul><li>Because most objects need initial values.</li></ul><p>Example:</p><pre>class Person:<br>  def __init__(self,name,age):<br>    self.name = name<br>    self.age = age</pre><p>Now create objects:</p><pre>p1 = Person(&quot;ABC&quot;,25)<br>p1 = Person(&quot;DEF&quot;,30)<br><br>print(p1.name)<br>print(p1.age)</pre><p>What Happens Internally?</p><p>When you write:</p><pre>p1 = Person(&quot;ABC&quot;,25)</pre><p>Python internally does something like:</p><pre>Person.__init__(p1, &quot;ABC&quot;, 25)</pre><p>so:</p><ul><li>self → refers to p1</li><li>“ABC” → assigned to self.name</li><li>25 → assigned to self.age</li></ul><p>The constructor ensures each object gets its own data.</p><h3>Understanding the ‘self’ Keyword</h3><p>self refers to the current object.</p><p><strong>It allows an object to:</strong></p><ul><li>Store its own data</li><li>Access its own methods</li><li>Differentiate between different instances</li></ul><p><strong>Important points:</strong></p><ul><li>self is not a keyword — it’s a convention.</li><li>It must always be the first parameter of instance methods.</li><li>It represents the calling object.</li></ul><p>Example:</p><pre>class Student:<br>    def __init__(self, name):<br>        self.name = name<br><br>    def display(self):<br>        print(&quot;Name:&quot;, self.name)</pre><p>Usage:</p><pre>s1 = Student(&quot;ABC&quot;)<br>s1.display()</pre><p>Here:</p><ul><li>self.name refers specifically to s1’s name.</li><li>If we create another object, it will have its own separate data.</li></ul><h3>Instance variables</h3><p>Instance variables are variables that belong to an object.</p><p>They are defined using self.</p><p>Example:</p><pre>class Car:<br>    def __init__(self, brand, price):<br>        self.brand = brand<br>        self.price = price</pre><p>Here:</p><ul><li>brand and price are instance variables.</li><li>Every object will have its own copy.</li></ul><p>Example:</p><pre>c1 = Car(&quot;BMW&quot;, 5000000)<br>c2 = Car(&quot;Audi&quot;, 4500000)<br><br>print(c1.brand)  # BMW<br>print(c2.brand)  # Audi</pre><p>Each object maintains its own state.</p><h3>Instance Methods</h3><p>Instance methods are functions defined inside a class that operate on instance variables.</p><p>They always include self as the first parameter.</p><p>Example:</p><pre>class BankAccount:<br>    def __init__(self, holder, balance):<br>        self.holder = holder<br>        self.balance = balance<br><br>    def deposit(self, amount):<br>        self.balance += amount<br><br>    def check_balance(self):<br>        print(&quot;Current Balance:&quot;, self.balance)</pre><p>Usage:</p><pre>acc1 = BankAccount(&quot;ABC&quot;, 10000)<br>acc1.deposit(2000)<br>acc1.check_balance()</pre><p>The method deposit() modifies that specific object&#39;s balance.</p><h3>Object Lifecycle in Python</h3><p>Understanding object lifecycle is crucial for advanced programming.</p><p>An object goes through these stages:</p><h4>1. Creation</h4><p>When you call the class:</p><pre>p1 = Person(&quot;ABC&quot;, 25)</pre><ul><li>Memory is allocated.</li><li>__init__() initializes the object.</li></ul><h4>2. Usage</h4><p>The object interacts with methods:</p><pre>p1.greet()</pre><p>During this phase:</p><ul><li>Attributes can be modified.</li><li>Methods can be called.</li><li>Object participates in program logic.</li></ul><h4>3. Destruction</h4><p>When an object is no longer referenced, Python’s garbage collector removes it.</p><p>You can manually delete:</p><pre>del p1</pre><p>There is also a special method called __del__() (destructor):</p><pre>class Demo:<br>    def __del__(self):<br>        print(&quot;Object destroyed&quot;)</pre><p>But in modern Python, manual memory management is rarely required.</p><p>Python automatically handles memory cleanup using garbage collection.</p><h4>Putting It All Together</h4><pre>class Laptop:<br>    def __init__(self, brand, ram):<br>        self.brand = brand<br>        self.ram = ram<br><br>    def upgrade_ram(self, extra):<br>        self.ram += extra<br><br>    def display(self):<br>        print(f&quot;Brand: {self.brand}, RAM: {self.ram}GB&quot;)</pre><p>Usage:</p><pre>l1 = Laptop(&quot;Dell&quot;, 8)<br>l1.display()<br><br>l1.upgrade_ram(8)<br>l1.display()</pre><p>This example demonstrates:</p><ul><li>Class creation</li><li>Object creation</li><li>Constructor</li><li>Instance variables</li><li>Instance methods</li><li>State modification</li></ul><h4>Final Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*-0WdkdUGo7gdoe6uzMW_Yw.png" /></figure><h3>Questions</h3><ol><li>What is a class in Python?</li><li>What is an object?</li><li>What is the difference between a class and an object?</li><li>How do you create a class in Python?</li><li>How do you create an object from a class?</li><li>What is the purpose of the __init__() method?</li><li>What is the role of the self keyword?</li><li>What are instance variables?</li><li>What are instance methods?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li><li><a href="https://medium.com/@sams.article/object-oriented-programming-oop-in-python-7f1fe4bca89f">Object-Oriented Programming (OOP) in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4119939735fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming (OOP) in Python]]></title>
            <link>https://medium.com/@sams.article/object-oriented-programming-oop-in-python-7f1fe4bca89f?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f1fe4bca89f</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop-python]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 06:22:25 GMT</pubDate>
            <atom:updated>2026-04-21T04:55:56.355Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore Object-Oriented Programming (OOP) in Python from the ground up — starting with basic programming paradigms and gradually moving toward advanced concepts like abstract base classes, magic methods, dataclasses, and best practices.</p><p>Object-Oriented Programming is one of the most powerful programming paradigms used in modern software development. Whether you’re preparing for interviews, building scalable applications, or aiming to write clean and reusable code, mastering OOP is essential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*oSgw5FzJyBQGC9tmNynyIg.png" /></figure><ol><li><a href="https://medium.com/@sams.article/programming-paradigms-267dd3eebc44"><strong>Programming Paradigms</strong></a><br>- Procedural vs Object-Oriented Programming<br>- Why OOP?<br>- Real-world modeling concepts<br>- OOP terminology (Class, Object, Attribute, Method)</li><li><a href="https://medium.com/@sams.article/classes-and-objects-in-python-4119939735fe"><strong>Classes &amp; Objects</strong></a><br>- Creating classes<br>- Creating objects<br>- __init__() constructor<br>- self keyword<br>- Instance variables<br>- Instance methods<br>- Object lifecycle</li><li><a href="https://medium.com/@sams.article/class-vs-instance-attributes-5fc68a0327a7"><strong>Class vs Instance Attributes</strong></a><br>- Class variables<br>- Instance variables<br>- Modifying class attributes<br>- Namespaces<br>- Memory structure overview</li><li><a href="https://medium.com/@sams.article/magic-dunder-methods-in-python-ae4840d87845"><strong>Magic (Dunder) Methods Basics</strong></a><br>- __str__<br>- __repr__<br>- __len__<br>- __del__<br>- __eq__</li><li><a href="https://medium.com/@sams.article/4-pillars-of-object-oriented-programming-oop-19d5ada7196d"><strong>The 4 Pillars of OOP</strong></a><br>- Encapsulation<br>- Abstraction<br>- Inheritance<br>- Polymorphism</li><li><strong>Access Modifiers</strong><br>- Public<br>- Protected<br>- Private<br>- Name mangling<br>- Getters and Setters<br>- @property decorator</li><li><strong>Inheritance Deep Dive</strong><br>- Single Inheritance<br>- Multiple Inheritance<br>- Multilevel Inheritance<br>- Hierarchical Inheritance<br>- Method Overriding<br>- super() function<br>- MRO (Method Resolution Order)</li><li><strong>Polymorphism</strong><br>- Method overriding<br>- Duck typing<br>- Operator overloading<br>- Function overloading techniques in Python</li><li><strong>Abstract Base Classes</strong><br>- abc module<br>- @abstractmethod<br>- Enforcing method implementation</li><li><strong>Composition vs Inheritance</strong><br>- Has-A vs Is-A relationship<br>- When to use composition<br>- Dependency injection basics</li><li><strong>Static &amp; Class Methods</strong><br>- @staticmethod<br>- @classmethod<br>- Factory methods</li><li><strong>Advanced Magic Methods</strong><br>- __add__<br>- __sub__<br>- __getitem__<br>- __setitem__<br>- __call__<br>- __enter__ / __exit__<br>- Custom iterators</li><li><strong>Dataclasses</strong><br>- @dataclass<br>- Field types<br>- Default values<br>- Frozen dataclasses</li><li><strong>Object-Oriented Best Practices</strong><br>- Clean class design<br>- Avoiding God objects<br>- Code reusability techniques<br>- Code smells in OOP<br>- Refactoring techniques</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f1fe4bca89f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Programming Paradigms]]></title>
            <link>https://medium.com/@sams.article/programming-paradigms-267dd3eebc44?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/267dd3eebc44</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming-paradigms]]></category>
            <category><![CDATA[python-oops-concept]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 06:21:07 GMT</pubDate>
            <atom:updated>2026-04-03T06:23:26.258Z</atom:updated>
            <content:encoded><![CDATA[<p>Programming paradigms are different styles or approaches to writing software. They define how you structure code, how you organize logic, and how you model real-world problems.</p><p>Two of the most important paradigms every developer must understand are:</p><ul><li>Procedural Programming</li><li>Object-Oriented Programming (OOP)</li></ul><p>Modern languages like Python support both paradigms, which makes understanding their differences even more important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*2uOLWA3_aGWKiZvVvDz7jg.png" /></figure><h3>Procedural vs Object-Oriented Programming</h3><h4>1. What is Procedural Programming?</h4><p>Procedural Programming is based on writing procedures (functions) that operate on data.</p><p>It follows a step-by-step execution flow, where the program runs from top to bottom.</p><p>Languages that strongly follow this paradigm include:</p><ul><li>C</li><li>Pascal</li></ul><h4>Key Characteristics:</h4><ul><li>Focus on functions</li><li>Data and functions are separate</li><li>Often uses global variables</li><li>Best for small programs and scripts</li></ul><h4>Example:</h4><pre>balance = 1000<br><br>def deposite(amount):<br>  global balance<br>  balance += amount<br><br>def withdraw(amount):<br>  global balance<br>  balance -= amount</pre><p>Here, functions modify shared global data.</p><h4>2. What is Object-Oriented Programming?</h4><p>Object-Oriented Programming (OOP) is based on objects, which combine data and behavior together.</p><p>Instead of focusing only on functions, OOP focuses on modeling real-world entities.</p><p>Languages that heavily use OOP:</p><ul><li>Java</li><li>C++</li></ul><h4>Key Characteristics:</h4><ul><li>Focus on objects</li><li>Data and methods bundled together</li><li>Better code organization</li><li>Highly scalable</li><li>Suitable for large applications</li></ul><h4>Example:</h4><pre>class BankAccount:<br>  def __init__(self,balance):<br>    self.balance = balance<br><br>  def deposit(self, amount):<br>    self.balance += amount<br><br>  def withdraw(self, amount):<br>    self.balance -= amount<br><br>account = BankAccount(1000)<br>account.deposit(500)</pre><p>Here, data (balance) belongs to the object, not the global scope.</p><p>— — — — — — — — — — — — — — — — — — —</p><h4>Comparison Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*wuelWGSzHivq1h__toVTKg.png" /></figure><h3>Why Object-Oriented Programming (OOP)?</h3><p>As software grows, procedural code becomes harder to manage.</p><p>OOP solves major real-world development problems:</p><ol><li><strong>Better Organization :</strong> Code is structured into classes and objects instead of scattered functions.</li><li><strong>Encapsulation : </strong>Data is protected and controlled. No unnecessary global access.</li><li><strong>Reusability </strong>: Through inheritance and composition, code can be reused efficiently.</li><li><strong>Scalability </strong>: Large systems like banking apps, e-commerce platforms, and enterprise software rely heavily on OOP.</li><li><strong>Team Collaboration :</strong> Different developers can work on separate classes/modules without interfering with each other.</li></ol><p><strong>In short:</strong> OOP is designed for long-term, scalable, maintainable software development.</p><h3>OOP Terminology (Class, Object, Attribute, Method)</h3><p>Understanding basic OOP terminology is essential.</p><h4>1. Class :</h4><ul><li>A Class is like an object constructor, or a “blueprint” for creating objects.</li><li>To create a class, use the keyword class</li></ul><pre>class Car:<br>  pass</pre><p>Think of it as a design template.</p><h4><strong>2. Object</strong></h4><ul><li>An instance of a class.</li></ul><pre>car1 = Car()</pre><p>If class is blueprint, object is the real product.</p><h4>3. Attribute</h4><ul><li>Variables that belong to a class or object.</li></ul><pre>class Car:<br>    def __init__(self, color):<br>        self.color = color</pre><p>Here, color is an attribute.</p><h4>4. Method</h4><ul><li>A function defined inside a class.</li></ul><pre>class Car:<br>    def start(self):<br>        print(&quot;Car started&quot;)</pre><p>Methods define behavior.</p><p>— — — — — — — — — — — — — — — — — — —</p><h4>Quick Summary Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*q4eT9ikcGXjqpf8SFTiB4w.png" /></figure><h3>Questions</h3><ol><li>What is a programming paradigm?</li><li>What is Procedural Programming?</li><li>What is Object-Oriented Programming?</li><li>Can Python support both procedural and OOP?</li><li>What is the main difference between Procedural and OOP?</li><li>Why is procedural programming not ideal for large systems?</li><li>Why is OOP preferred in enterprise applications?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li><li><a href="https://medium.com/@sams.article/object-oriented-programming-oop-in-python-7f1fe4bca89f">Object-Oriented Programming (OOP) in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=267dd3eebc44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[File Handling in Python]]></title>
            <link>https://medium.com/@sams.article/file-handling-in-python-b907b73441fc?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/b907b73441fc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-file-handling]]></category>
            <category><![CDATA[pythonnet]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[file-handling-in-python]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 11:10:58 GMT</pubDate>
            <atom:updated>2026-03-12T11:10:58.284Z</atom:updated>
            <content:encoded><![CDATA[<p>File handling allows Python programs to store data permanently in files instead of keeping it only in memory.</p><p>It is used for:</p><ul><li>Saving logs</li><li>Storing user data</li><li>Reading configuration files</li><li>Processing CSV/JSON data</li><li>Working with large datasets</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*Fj7DktEm_veUL7FRSCtU-g.png" /></figure><h3>What is File Handling?</h3><p>File handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely and efficiently.</p><h3>1. Opening a File</h3><p>To open a file, we can use open() function, which requires file-path and mode as arguments.</p><p>Syntax:</p><pre>file = open(&quot;filename&quot;, &quot;mode&quot;)<br># here,<br>  # filename : name (or path) of the file to be opened.<br>  # mode: mode in which you want to open the file (read, write, etc.).</pre><p>Example:</p><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;)<br># This code opens file data.txt in read mode. <br># If the file exists, it returns a file object <br># connected to that file; if the file does not exist, <br># Python raises a FileNotFoundError.</pre><ul><li>If you don’t specify the mode, Python uses ‘r’ (read mode) by default.</li></ul><p>— — — — — — — — — — — — — — — — — — -</p><h3>2. Closing a File</h3><p>The file.close() method closes the file and releases the system resources. If the file was opened in write or append mode, closing ensures that all changes are properly saved.</p><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;)<br>file.close()</pre><p>— — — — — — — — — — — — — — — — — — -</p><h3>3. Reading a File</h3><p>Reading a file can be achieved by file.read() which reads the entire content of the file. After reading, it’s good practice to close the file to free up system resources.</p><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;)<br>content = file.read()<br>print(content)<br>file.close()</pre><ol><li>read() – Read Entire File : Reads the full content as one string.</li></ol><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;)<br>content = file.read()<br>print(content)<br>file.close()</pre><p>You can also read specific number of characters:</p><pre>content = file.read(10)  # Reads first 10 characters</pre><p>2. readline() – Read One Line : Reads one line at a time.</p><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;)<br>line = file.readline()<br>print(line)<br>file.close()</pre><p>You can call it multiple times:</p><pre>print(file.readline())<br>print(file.readline())</pre><p>3. readlines() – Read All Lines into a List : Returns a list of lines.</p><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;)<br>lines = file.readlines()<br>print(lines)<br>file.close()<br># output<br>  # [&#39;Line 1\n&#39;, &#39;Line 2\n&#39;, &#39;Line 3\n&#39;]</pre><h4><strong>Reading File Line by Line</strong></h4><p>Best for large files:</p><pre>with open(&quot;data.txt&quot;, &quot;r&quot;) as file:<br>    for line in file:<br>        print(line.strip())</pre><p>Why this is better?</p><ul><li>Memory efficient</li><li>Reads one line at a time</li></ul><h4>Encoding While Opening File</h4><p>Sometimes needed for Unicode text:</p><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;)</pre><p>Important when working with:</p><ul><li>Hindi / Gujarati text</li><li>Special symbols</li><li>International data</li></ul><p>— — — — — — — — — — — — — — — — — — -</p><h3>4. Writing a File</h3><p>In Python, writing to a file is done using the mode “w”. This creates a new file if it doesn’t exist, or overwrites the existing file if it does. The write() method is used to add content. After writing, make sure to close the file.</p><pre>with open(&quot;geek.txt&quot;, &quot;w&quot;) as file:<br>    file.write(&quot;Hello, Python!\n&quot;)<br>    file.write(&quot;File handling is easy with Python.&quot;)<br><br>print(&quot;File written successfully&quot;)</pre><ul><li>“w” mode opens the file for writing (overwrites existing content if the file already exists).</li><li>write() method adds new text to the file.</li><li>When using with, the file closes automatically at the end of the block.</li></ul><h4>File Modes for Writing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*f3Bt_F5XRYuHCjqxB1Z0Pw.png" /></figure><p>writelines() : Writing Multiple Lines</p><pre>lines = [&quot;Line 1\n&quot;, &quot;Line 2\n&quot;, &quot;Line 3\n&quot;]<br><br>with open(&quot;data.txt&quot;, &quot;w&quot;) as file:<br>    file.writelines(lines)</pre><ul><li>writelines() does NOT add \n automatically.</li><li>You must include newline manually.</li></ul><h3>Checking File Properties</h3><p>Once the file is open, we can check some of its properties:</p><pre>f = open(&quot;data.txt&quot;, &quot;r&quot;)<br>print(&quot;Filename:&quot;, f.name)<br>print(&quot;Mode:&quot;, f.mode)<br>print(&quot;Is Closed?&quot;, f.closed)</pre><pre>f.close()<br>print(&quot;Is Closed?&quot;, f.closed)</pre><ul><li><strong>f.name:</strong> Returns the name of the file that was opened (in this case, “data.txt”).</li><li><strong>f.mode:</strong> Tells us the mode in which the file was opened. Here, it’s ‘r’ which means read mode.</li><li><strong>f.closed: </strong>Returns a boolean value- False when file is currently open otherwise True.</li></ul><h3>Using with Statement in Python</h3><p>The with statement is the <strong>best and safest way</strong> to work with files in Python.</p><p>It automatically handles <strong>opening and closing</strong> of files.</p><p>syntax:</p><pre>with open(&quot;filename&quot;, &quot;mode&quot;) as variable:<br>    # block of code</pre><p>Example:</p><pre>with open(&quot;data.txt&quot;, &quot;r&quot;) as file:<br>    content = file.read()<br>    print(content)</pre><h4>Why Use with</h4><p>Without with:</p><pre>file = open(&quot;data.txt&quot;, &quot;r&quot;)<br>content = file.read()<br>file.close()</pre><p>Problems:</p><ul><li>If an error occurs before close(), file remains open</li><li>Can cause memory leaks</li><li>Bad practice in production</li></ul><p>With with:</p><pre>with open(&quot;data.txt&quot;, &quot;r&quot;) as file:<br>    content = file.read()</pre><ul><li>Automatically closes file</li><li>Safer</li><li>Cleaner</li><li>Industry standard</li></ul><h4>Multiple Files in One with</h4><pre>with open(&quot;source.txt&quot;, &quot;r&quot;) as source, open(&quot;dest.txt&quot;, &quot;w&quot;) as dest:<br>    data = source.read()<br>    dest.write(data)</pre><ul><li>Both files close automatically</li><li>Useful for file copying</li></ul><h3>Working with Binary Files in Python</h3><p>Binary files store data in raw byte format, not readable text.</p><p>Examples:</p><ul><li>Images (.jpg, .png)</li><li>PDFs (.pdf)</li><li>Videos (.mp4)</li><li>Audio (.mp3)</li><li>Executables (.exe)</li></ul><p>Unlike text files, binary files are handled using binary mode (b).</p><h4>1. Opening a Binary File</h4><pre>open(&quot;filename&quot;, &quot;rb&quot;)   # Read binary<br>open(&quot;filename&quot;, &quot;wb&quot;)   # Write binary<br>open(&quot;filename&quot;, &quot;ab&quot;)   # Append binary</pre><h4>2. Reading a Binary File</h4><pre>with open(&quot;image.jpg&quot;, &quot;rb&quot;) as file:<br>    data = file.read()<br>    print(data[:50])  # First 50 bytes</pre><h4>3. Writing a Binary File</h4><pre>with open(&quot;image.jpg&quot;, &quot;rb&quot;) as source:<br>    data = source.read()<br><br>with open(&quot;copy.jpg&quot;, &quot;wb&quot;) as dest:<br>    dest.write(data)</pre><h4>4. Reading Large Binary Files</h4><pre>with open(&quot;video.mp4&quot;, &quot;rb&quot;) as file:<br>    while True:<br>        chunk = file.read(1024)  # 1 KB chunk<br>        if not chunk:<br>            break<br>        print(len(chunk))</pre><h3>Buffering</h3><p>When you open a file, Python does <strong>not</strong> read/write directly to disk every time.</p><p>Why buffering?</p><ul><li>Reduces disk I/O</li><li>Improves speed</li><li>Minimizes system calls</li></ul><h4>Control Buffering</h4><pre>open(&quot;data.txt&quot;, &quot;r&quot;, buffering=1024)   # 1KB buffer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*o3BrWLm-uvtI_8SbAgrSKQ.png" /></figure><h3>File Pointer (seek() &amp; tell())</h3><p>tell()</p><ul><li>Returns current byte position.</li></ul><p>seek(offset, whence)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*Uj5j3lbaOGv1O-tjasJZMg.png" /></figure><p>Example:</p><pre>with open(&quot;data.txt&quot;, &quot;rb&quot;) as f:<br>    f.seek(5)<br>    print(f.read(10))</pre><p>Reverse Reading Example:</p><pre>with open(&quot;data.txt&quot;, &quot;rb&quot;) as f:<br>    f.seek(-10, 2)  # Last 10 bytes<br>    print(f.read())</pre><p>seek() with negative offset works only in binary mode.</p><h3>Handling Very Large Files</h3><p>❌ Bad:</p><pre>data = file.read()  # Loads everything into memory</pre><p>✔ Good:</p><pre>with open(&quot;bigfile.txt&quot;) as f:<br>    for line in f:<br>        process(line)</pre><p>✔ Even Better (Chunk Reading):</p><pre>def read_in_chunks(file, chunk_size=1024):<br>    while chunk := file.read(chunk_size):<br>        yield chunk<br>with open(&quot;bigfile.txt&quot;) as f:<br>    for chunk in read_in_chunks(f):<br>        process(chunk)</pre><h3>Asynchronous File Handling (Async I/O)</h3><p>Useful in:</p><ul><li>Web servers</li><li>High-concurrency apps</li></ul><p>Using aiofiles:</p><pre>import aiofiles<br>import asyncio<br><br>async def read_file():<br>    async with aiofiles.open(&quot;data.txt&quot;, &quot;r&quot;) as f:<br>        content = await f.read()<br>        print(content)<br><br>asyncio.run(read_file())</pre><h3>Working with Compressed Files</h3><p>Compressed files reduce file size and are commonly used for:</p><ul><li>Backups</li><li>Data transfer</li><li>Logs</li><li>Large datasets</li><li>Software distribution</li></ul><p>Python provides built-in modules to work with compressed files directly without manually extracting them.</p><h4>1. Working with ZIP Files (zipfile Module)</h4><p>Python provides the built-in zipfile module.</p><ul><li><strong>Creating a ZIP File</strong></li></ul><pre>import zipfile<br><br>with zipfile.ZipFile(&quot;archive.zip&quot;, &quot;w&quot;) as zipf:<br>    zipf.write(&quot;data.txt&quot;)</pre><p>Creates archive.zip<br>Adds data.txt inside it</p><ul><li><strong>Adding Multiple Files</strong></li></ul><pre>import zipfile<br><br>with zipfile.ZipFile(&quot;archive.zip&quot;, &quot;w&quot;) as zipf:<br>    zipf.write(&quot;file1.txt&quot;)<br>    zipf.write(&quot;file2.txt&quot;)</pre><ul><li><strong>Extracting ZIP File</strong></li></ul><pre>import zipfile<br><br>with zipfile.ZipFile(&quot;archive.zip&quot;, &quot;r&quot;) as zipf:<br>    zipf.extractall(&quot;extracted_folder&quot;)</pre><ul><li><strong>Reading a File Inside ZIP (Without Extracting)</strong></li></ul><pre>import zipfile<br><br>with zipfile.ZipFile(&quot;archive.zip&quot;, &quot;r&quot;) as zipf:<br>    with zipf.open(&quot;data.txt&quot;) as file:<br>        print(file.read().decode(&quot;utf-8&quot;))</pre><p>Very useful for large datasets<br>No need to manually unzip</p><p>— — — — — — — — — — — — — — — — —</p><h4>2. Working with GZIP Files (gzip Module)</h4><p>Used for .gz files (commonly for logs and large data).</p><ul><li>Writing GZIP File</li></ul><pre>import gzip<br><br>with gzip.open(&quot;data.txt.gz&quot;, &quot;wt&quot;) as file:<br>    file.write(&quot;Hello Compressed World&quot;)</pre><p>&quot;wt&quot; → Write Text<br> &quot;wb&quot; → Write Binary</p><ul><li>Reading GZIP File</li></ul><pre>import gzip<br><br>with gzip.open(&quot;data.txt.gz&quot;, &quot;rt&quot;) as file:<br>    print(file.read())</pre><p>Common in:</p><p>— Log compression</p><p>— Data pipelines</p><p>— Big data processing</p><p>— — — — — — — — — — — — — — — — —</p><h4>3. Working with TAR Files (tarfile Module)</h4><p>Used for .tar, .tar.gz, .tgz</p><ul><li>Creating TAR Archive</li></ul><pre>import tarfile<br><br>with tarfile.open(&quot;archive.tar&quot;, &quot;w&quot;) as tar:<br>    tar.add(&quot;data.txt&quot;)</pre><ul><li>Creating Compressed TAR (tar.gz)</li></ul><pre>import tarfile<br><br>with tarfile.open(&quot;archive.tar.gz&quot;, &quot;w:gz&quot;) as tar:<br>    tar.add(&quot;data.txt&quot;)</pre><ul><li>Extracting TAR</li></ul><pre>import tarfile<br><br>with tarfile.open(&quot;archive.tar.gz&quot;, &quot;r:gz&quot;) as tar:<br>    tar.extractall(&quot;output_folder&quot;)</pre><h3>Questions</h3><ol><li>What is file handling?</li><li>Difference between w and a mode?</li><li>What is with statement?</li><li>Difference between read() and readlines()?</li><li>What happens if file doesn’t exist in r mode?</li><li>Explain file pointer.</li><li>What is buffering?</li><li>Difference between text and binary mode?</li><li>Difference between ZIP and GZIP?</li><li>What problem does with solve?</li><li>Can we open multiple files in one with?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b907b73441fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception Handling in Python]]></title>
            <link>https://medium.com/@sams.article/exception-handling-in-python-677967740aec?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/677967740aec</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python-exception]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 05:39:06 GMT</pubDate>
            <atom:updated>2026-03-10T05:39:06.946Z</atom:updated>
            <content:encoded><![CDATA[<p>Exception Handling is used to handle <strong>runtime errors</strong> gracefully without crashing the program. Instead of stopping execution, Python allows us to <strong>catch errors and handle them properly</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*fTAo49BlPdxnrztDEfdp1g.png" /></figure><h3>What is an Exception?</h3><p>An <strong>Exception</strong> is an error that occurs during program execution.</p><p><strong>Example:</strong></p><pre>print(10 / 0)   # ZeroDivisionError<br># otput:<br>  # ZeroDivisionError: division by zero</pre><ul><li>Python stops the program because the error is not handled.</li></ul><h4>Why Exception Handling is Important?</h4><ul><li>Prevents program crash</li><li>Improves user experience</li><li>Helps debugging</li><li>Maintains program flow</li><li>Makes code professional</li></ul><h4>Syntax:</h4><pre>try:<br>    # Code that may cause error<br>except:<br>    # Code that runs if error occurs</pre><h4>Example:</h4><pre>try:<br>    num = int(input(&quot;Enter number: &quot;))<br>    print(10 / num)<br>except:<br>    print(&quot;Error occurred!&quot;)</pre><ul><li>If user enters 0 or invalid input, program won’t crash.</li></ul><h4>How try-except Works:</h4><ul><li>Python executes code inside try</li><li>If error occurs → jumps to except</li><li>If no error → except block is skipped</li></ul><h4>Handling Specific Exceptions</h4><pre>try:<br>    num = int(input(&quot;Enter number: &quot;))<br>    print(10 / num)<br><br>except ZeroDivisionError:<br>    print(&quot;You cannot divide by zero!&quot;)<br><br>except ValueError:<br>    print(&quot;Invalid input! Please enter a number.&quot;)</pre><ul><li>Always catch <strong>specific exceptions</strong>, not generic ones.</li></ul><h3>Common Built-in Exceptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*rvfdl3njK6e4yl7tuv2D8w.png" /></figure><h3>Using “as” to Get Error Message</h3><pre>try:<br>    print(10 / 0)<br>except ZeroDivisionError as e:<br>    print(&quot;Error:&quot;, e)</pre><h4>except ZeroDivisionError as e</h4><ul><li>Python catches the error.</li><li>The error object is stored in variable e.</li><li>e contains the message: “division by zero”</li></ul><h4>Why Use &quot;as e”?</h4><p>Using as e allows you to:</p><ul><li>Access the exact error message</li><li>Log the error</li><li>Debug efficiently</li><li>Show user-friendly error messages</li><li>Inspect error details</li></ul><h3>else Block</h3><p>else runs <strong>only if no exception occurs</strong>.</p><pre>try:<br>    num = int(input(&quot;Enter number: &quot;))<br>except ValueError:<br>    print(&quot;Invalid input&quot;)<br>else:<br>    print(&quot;You entered:&quot;, num)</pre><h3>finally Block</h3><p>finally always runs (error or no error).</p><p>Used for:</p><ul><li>Closing files</li><li>Closing database connections</li><li>Cleaning resources</li></ul><pre>try:<br>    f = open(&quot;data.txt&quot;)<br>except FileNotFoundError:<br>    print(&quot;File not found&quot;)<br>finally:<br>    print(&quot;Execution completed&quot;)</pre><h4>Full Structure</h4><pre>try:<br>    # risky code<br>except ExceptionType1:<br>    # handle error<br>except ExceptionType2:<br>    # handle error<br>else:<br>    # runs if no error<br>finally:<br>    # always runs</pre><h4>Raising Exceptions (raise)</h4><p>You can manually create exceptions.</p><pre>age = int(input(&quot;Enter age: &quot;))<br><br>if age &lt; 18:<br>    raise ValueError(&quot;Age must be 18 or above&quot;)<br><br>print(&quot;Eligible&quot;)</pre><h3>Creating Custom Exception</h3><pre>class InvalidAgeError(Exception):<br>    pass<br><br>age = int(input(&quot;Enter age: &quot;))<br><br>if age &lt; 18:<br>    raise InvalidAgeError(&quot;Too young!&quot;)</pre><h4>Using Exception Class</h4><pre>try:<br>    print(10 / 0)<br>except Exception as e:<br>    print(&quot;Something went wrong:&quot;, e)</pre><ul><li>Exception is the base class of all exceptions.</li></ul><h3>Nested try-except</h3><pre>try:<br>    try:<br>        print(10 / 0)<br>    except ZeroDivisionError:<br>        print(&quot;Inner handled&quot;)<br>except:<br>    print(&quot;Outer handled&quot;)</pre><h3>Best Practices</h3><ul><li>Catch specific exceptions</li><li>Avoid empty except block</li><li>Use finally for cleanup</li><li>Don’t overuse try-except</li><li>Log errors in real projects</li></ul><h3>Real-World Example</h3><pre>try:<br>    with open(&quot;data.txt&quot;, &quot;r&quot;) as f:<br>        data = f.read()<br>except FileNotFoundError:<br>    print(&quot;File does not exist&quot;)<br>except PermissionError:<br>    print(&quot;No permission to read file&quot;)<br>else:<br>    print(&quot;File content loaded successfully&quot;)<br>finally:<br>    print(&quot;Operation finished&quot;)</pre><h3>Logging Exceptions</h3><p>In real-world applications, we don’t just print errors — we <strong>log them</strong>.</p><p>Python provides the built-in module: logging</p><h4><strong>Why Use Logging Instead of print()?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*HDqwwlzItjU3m9I8EeCsJg.png" /></figure><p><strong>Basic Logging Example</strong></p><pre>import logging<br><br>logging.basicConfig(<br>    filename=&quot;app.log&quot;,<br>    level=logging.ERROR,<br>    format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;<br>)<br><br>try:<br>    10 / 0<br>except ZeroDivisionError as e:<br>    logging.error(&quot;Division failed&quot;, exc_info=True)</pre><p><strong>What Happens?</strong></p><ul><li>Error stored in app.log</li><li>Stack trace saved</li><li>Program continues safely</li></ul><h4>Logging Levels</h4><pre>logging.debug(&quot;Debug info&quot;)<br>logging.info(&quot;Information&quot;)<br>logging.warning(&quot;Warning message&quot;)<br>logging.error(&quot;Error occurred&quot;)<br>logging.critical(&quot;Critical issue&quot;)</pre><h3>Custom Exception Hierarchy</h3><p>In large systems, we don’t use generic ValueError.<br>We create our <strong>own structured exception system</strong>.</p><p><strong>Example : E-commerce Application</strong></p><pre>class AppError(Exception):<br>    &quot;&quot;&quot;Base class for all application errors&quot;&quot;&quot;<br>    pass<br><br><br>class DatabaseError(AppError):<br>    pass<br><br><br>class PaymentError(AppError):<br>    pass<br><br><br>class ValidationError(AppError):<br>    pass</pre><p><strong>Usage</strong></p><pre>def process_payment(amount):<br>    if amount &lt;= 0:<br>        raise ValidationError(&quot;Invalid payment amount&quot;)<br><br>    raise PaymentError(&quot;Payment gateway not responding&quot;)<br><br><br>try:<br>    process_payment(-10)<br><br>except ValidationError as e:<br>    print(&quot;Validation failed:&quot;, e)<br><br>except PaymentError as e:<br>    print(&quot;Payment issue:&quot;, e)<br><br>except AppError as e:<br>    print(&quot;General app error:&quot;, e)</pre><p><strong>Why Custom Hierarchy?</strong></p><ul><li>Centralized error management</li><li>Cleaner architecture</li><li>Easier debugging</li><li>Enterprise-ready structure</li></ul><h3>Exception Chaining</h3><p>Sometimes one exception occurs <strong>because of another exception</strong>.</p><p>Python supports chaining using:</p><pre>raise NewException() from original_exception</pre><p><strong>Example Without Chaining</strong></p><pre>try:<br>    int(&quot;abc&quot;)<br>except ValueError:<br>    raise TypeError(&quot;Conversion failed&quot;)</pre><ul><li>You lose the original error cause</li></ul><p><strong>Example With Chaining</strong></p><pre>try:<br>    int(&quot;abc&quot;)<br>except ValueError as e:<br>    raise TypeError(&quot;Conversion failed&quot;) from e</pre><p><strong>Output shows:</strong></p><ul><li>Original ValueError</li><li>New TypeError</li><li>Full traceback chain</li></ul><p>This is extremely useful in large systems.</p><h3>Questions</h3><ol><li>What is the difference between error and exception?</li><li>What is the difference between except and finally?</li><li>Why should we avoid bare except?</li><li>What happens if an exception is not handled?</li><li>Difference between raise and assert?</li><li>Can we have multiple except blocks?</li><li>What is the base class of all exceptions?</li><li>When does else block execute?</li><li>What is exception chaining?</li><li>Difference between raise and raise from?</li><li>Why use custom exception hierarchy?</li><li>How does logging improve debugging?</li><li>When should we re-raise exceptions?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=677967740aec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrays in Python]]></title>
            <link>https://medium.com/@sams.article/arrays-in-python-95fc997d9309?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/95fc997d9309</guid>
            <category><![CDATA[python-array]]></category>
            <category><![CDATA[arrays-in-python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 06:40:07 GMT</pubDate>
            <atom:updated>2026-03-09T06:40:07.978Z</atom:updated>
            <content:encoded><![CDATA[<p>In Python, arrays are used to store multiple values in a single variable. However, Python does not have a built-in array type like C or Java. Instead, Python mainly uses:</p><ul><li>List (most common)</li><li>array module</li><li>NumPy arrays (for numerical computing)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*Kt86EnVg0RsZzAcuGJ1eCQ.png" /></figure><h3>What is an Array?</h3><p>An array is a data structure that:</p><ul><li>Stores multiple elements in a single variable</li><li>Elements are stored in sequential memory locations</li><li>Accessed using index numbers</li><li>Usually stores elements of the same type</li></ul><h3>Arrays Using Python Lists (Dynamic Arrays)</h3><p>In Python, <strong>lists act as dynamic arrays</strong>.</p><pre>arr = [10, 20, 30, 40]<br><br>print(arr[0])   # 10<br>print(arr[2])   # 30</pre><h4><strong>Characteristics of List-Based Arrays</strong></h4><ul><li>Ordered</li><li>Mutable (can change values)</li><li>Dynamic size (can grow/shrink)</li><li>Allows duplicate values</li><li>Can store multiple data types</li></ul><h3>The array Module in Python (Typed Arrays)</h3><p>Python provides the <strong>array module</strong> to create <strong>typed arrays</strong> (arrays that store elements of the same data type).</p><pre>from array import array</pre><h4><strong>Creating a Typed Array</strong></h4><pre>array(typecode, iterable)</pre><pre>from array import array<br>arr = array(&quot;i&quot;, [10,20,30,40])<br>print(arr)<br># ouput<br>  # array(&#39;i&#39;, [10, 20, 30, 40])</pre><h4><strong>Type Codes</strong></h4><ul><li>Type code defines what data type the array can store.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*P3fZjY3Md_xf-T3UzNbyhA.png" /></figure><h4>Why Use Typed Arrays Instead of List?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*6J01oU6ToTGEHTvbRqUVig.png" /></figure><h3>Accessing Elements</h3><ol><li>Positive Indexing</li></ol><pre>arr = [10,20,30,40]<br>print(arr[1])<br># 20</pre><p>2. Negative Indexing</p><pre>arr = [10,20,30,40]<br>print(arr[-1])  # 40</pre><h3>Traversing an Array</h3><ul><li>Using for loop</li></ul><pre>arr = [10,20,30,40]<br>for element in arr:<br>    print(element)<br># ouput<br>  # 10<br>  # 20<br>  # 30<br>  # 40</pre><ul><li>Using index</li></ul><pre>arr = [10,20,30,40]<br>for i in range(len(arr)):<br>    print(arr[i])<br># ouput<br>  # 10<br>  # 20<br>  # 30<br>  # 40</pre><h3>Updating Elements</h3><pre>arr = [10, 20, 30]<br>arr[1] = 25<br>print(arr)<br># ouput:<br>  # [10, 25, 30]</pre><h3>Adding Elements</h3><ol><li><strong>append() — Add at the End</strong></li></ol><ul><li>Adds a single element to the end of the array.</li></ul><pre>arr.append(40)<br>print(arr)</pre><ul><li>Used when you want to grow array from the end.</li></ul><p><strong>2. insert() — Add at Specific Position</strong></p><pre>arr.insert(1, 15)   # Insert 15 at index 1<br>print(arr)</pre><ul><li>Useful when position matters.</li></ul><p><strong>3. extend() — Add Multiple Elements</strong></p><ul><li>Adds multiple elements at once.</li></ul><pre>arr.extend([50, 60])<br>print(arr)</pre><ul><li>Efficient for bulk insertion.</li></ul><h4>Important Rules</h4><ul><li>You can only add elements of the same data type.</li><li>If array type is ‘i’ (integer), you cannot add float or string.</li></ul><h3>Internal Working</h3><p>Python arrays:</p><ul><li>Are stored in contiguous memory</li><li>Have fixed data type</li><li>When size increases → memory may be reallocated internally</li></ul><h3>Removing Elements</h3><ol><li><strong>remove() — Remove by Value</strong></li></ol><ul><li>Removes the <strong>first occurrence</strong> of a value.</li></ul><pre>arr.remove(30)<br>print(arr)</pre><p><strong>2. pop() — Remove by Index</strong></p><ul><li>Removes element using <strong>index position</strong>.</li><li>If no index is given → removes <strong>last element</strong></li></ul><pre>arr.pop(1)<br>print(arr)</pre><p><strong>3. del Statement — Delete by Index or Slice</strong></p><ul><li>Delete single element</li></ul><pre>del arr[0]</pre><ul><li>Delete multiple elements (slicing)</li></ul><pre>del arr[1:3]</pre><p><strong>4. clear() — Remove All Elements</strong></p><ul><li>Unlike list, array does NOT have direct .clear() method.</li></ul><pre>arr = array(&#39;i&#39;)   # Reinitialize</pre><h4>Internal Working (Interview Important)</h4><ul><li>Arrays store elements in contiguous memory</li><li>When removing an element: All elements after it are shifted left</li></ul><h3>Questions</h3><ol><li>What is an array in Python?</li><li>How is list different from array module?</li><li>Why are Python lists called dynamic arrays?</li><li>What is the difference between append() and extend()?</li><li>Can we insert different data types in Python array?</li><li>What is the difference between remove() and pop()?</li><li>Can we remove elements using slicing?</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95fc997d9309" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set in Python]]></title>
            <link>https://medium.com/@sams.article/set-in-python-cfc4236530fb?source=rss-a731cc558870------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfc4236530fb</guid>
            <category><![CDATA[python-set]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[set-in-python]]></category>
            <dc:creator><![CDATA[Saurabh Gandhi]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 14:55:22 GMT</pubDate>
            <atom:updated>2026-03-06T14:55:22.736Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>set</strong> in Python is a built-in data type used to store <strong>multiple unique values</strong> in a single variable.</p><p>It is mainly used when:</p><ul><li>You want to avoid duplicate values</li><li>You need fast searching</li><li>You want to perform mathematical set operations like union and intersection</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*Fd-K95jSKEprMnaYynsEnw.png" /></figure><h3>What is a Set?</h3><p>A set is a collection of unique elements.</p><ul><li>Unordered: Items are not stored in a particular order.</li><li>Mutable: You can add or remove elements.</li><li>No duplicate elements: Each item appears only once.</li></ul><p>Example:</p><pre>my_set = {1, 2, 3, 4, 5}<br>print(my_set)  <br># Output: {1, 2, 3, 4, 5}</pre><h3>Creating a Set</h3><pre>s = set()<br><br># set with element<br>s = {1,2,3,4}<br><br># Duplicate values are automatically removed<br>s = {1,2,2,3,4}<br>print(s)<br># {1,2,3,4}</pre><p><strong>Note:</strong></p><ul><li>{} creates an empty dictionary</li><li>Use set() for an empty set</li></ul><h3>Characteristics of Set</h3><ul><li>Unordered</li><li>No indexing</li><li>No duplicates</li><li>Mutable (can be changed)</li><li>Elements must be <strong>immutable</strong> (no list inside set)</li></ul><h3>Accessing Elements</h3><p>Since sets are unordered, you <strong>cannot use index</strong>.</p><pre>s = {10, 20, 30}<br><br>for item in s:<br>    print(item)</pre><h3><strong>Adding Elements</strong></h3><ol><li>add() (Add One Element)</li></ol><pre>s = {1,2,3}<br>s.add(4)<br>print(s)<br># output<br>  # {1, 2, 3, 4}</pre><p>2. update() (Add Multiple Elements)</p><pre>s.update([5, 6, 7])<br>print(s)<br># ouput<br>  # {1, 2, 3, 5, 6, 7}</pre><h3>Removing Elements</h3><ol><li>remove()</li></ol><p>Removes an element.<br>Raises error if element does not exist.</p><pre>s.remove(2)<br>print(s)<br># output<br>  # {1, 3}</pre><p>2. discard()</p><p>Removes an element.<br> Does NOT raise error if element not found.</p><pre>s.discard(10)</pre><p>3. pop()</p><p>Removes a random element.</p><pre>s.pop()</pre><p>4. clear()</p><p>Removes all elements.</p><pre>s.clear()</pre><h3>Set Operations</h3><p>Sets support mathematical operations.</p><ol><li>Union (|)</li></ol><ul><li>Combines both sets.</li></ul><pre>A = {1, 2, 3}<br>B = {3, 4, 5}<br><br>print(A | B)<br># ouput<br>  # {1, 2, 3, 4, 5}</pre><p>2. Intersection (&amp;)</p><ul><li>Common elements only.</li></ul><pre>A = {1, 2, 3}<br>B = {3, 4, 5}<br><br>print(A &amp; B)<br># ouput<br>  # {3}</pre><p>3. Difference (-)</p><ul><li>Elements in first set but not in second.</li></ul><pre>A = {1, 2, 3}<br>B = {3, 4, 5}<br><br>print(A - B)<br># ouput<br>  # {1, 2}</pre><p>4. Symmetric Difference (^)</p><ul><li>Elements not common in both sets.</li></ul><pre>A = {1, 2, 3}<br>B = {3, 4, 5}<br><br>print(A ^ B)<br># ouput<br>  # {1, 2, 4, 5}</pre><h3>Frozen Set</h3><ul><li>If you want an <strong>immutable set</strong>, use frozenset().</li></ul><pre>fs = frozenset([1, 2, 3])<br>print(fs)</pre><p>Frozen sets:</p><ul><li>Cannot be modified</li><li>Can be used as dictionary keys</li></ul><h3>When Should You Use a Set?</h3><p>Use a set when:</p><ul><li>You need unique values</li><li>You want fast lookup</li><li>You need mathematical operations</li><li>Order does not matter</li></ul><h3>Questions</h3><ol><li>What is a set in Python?</li><li>Why are sets unordered?</li><li>Can sets contain duplicate values?</li><li>What is the difference between remove() and discard()?</li><li>What is the internal working of a set?</li><li>What is a frozenset?</li><li>Explain union, intersection, difference.</li></ol><h3>Table of Contents</h3><ul><li><a href="https://medium.com/@sams.article/python-for-beginners-7de4d508b9f2">Python: A Beginner’s Guide to Programming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfc4236530fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>