<?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 Chaanakya on Medium]]></title>
        <description><![CDATA[Stories by Chaanakya on Medium]]></description>
        <link>https://medium.com/@chaanakya?source=rss-c928edcd3e1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YP677vUXFH-fu1hjA6BaeQ.jpeg</url>
            <title>Stories by Chaanakya on Medium</title>
            <link>https://medium.com/@chaanakya?source=rss-c928edcd3e1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:03:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chaanakya/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[Comprehensive Guide to Python Data Structures]]></title>
            <link>https://medium.com/@chaanakya/comprehensive-guide-to-python-data-structures-4d608af376de?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d608af376de</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-data-structures]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 11:07:08 GMT</pubDate>
            <atom:updated>2025-04-24T11:07:08.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Python offers a variety of built-in data structures, each with its own characteristics that make them well-suited for different kinds of tasks. U In this guide, we’ll brief each of these data structures, how they work internally, and their associated methods along with time complexities.</p><h3>Characteristics of Python Data Structures</h3><h4>Ordering</h4><p>Ordering determines whether the structure retains the sequence of elements as they are added. Lists, tuples, and dictionaries maintain the insertion order, which is beneficial when order matters. Sets do not, as they focus on element uniqueness.</p><h4>Mutability</h4><p>Mutability describes whether a data structure can be modified after creation without creating a copy. Mutable structures like lists, sets, and dictionaries are great for dynamic workloads. Tuples, being immutable, are excellent for read-only operations to ensure data integrity or to prevent accidental modification.</p><h4>Hashing</h4><p>Hashing is relevant for sets and dictionaries, where a hash function is used to quickly locate elements. This makes operations like lookup nearly instantaneous. Hashable items are crucial for efficient searching and data retrieval.</p><h4>Indexing</h4><p>Indexing allows direct access to an element via an integer index or key. Lists and tuples are indexed by integers, enabling direct element retrieval. Dictionaries provide key-based indexing, allowing access via a key, which makes them highly versatile for mapping operations.</p><p>Lets look at each data structure now.</p><h3>Lists</h3><ul><li><strong>Ordering</strong>: Yes. Lists maintain the order of elements as they are inserted.</li><li><strong>Mutability</strong>: Mutable. You can change elements, add new elements, or remove elements.</li><li><strong>Hashing</strong>: Not hashable. Lists cannot be used as keys in dictionaries.</li><li><strong>Indexing</strong>: Supports indexing, allowing access to elements by position.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ffb4ebf4b5fd8566f4472f9eaa86158/href">https://medium.com/media/7ffb4ebf4b5fd8566f4472f9eaa86158/href</a></iframe><p>To read more about lists:</p><p><a href="https://medium.com/@chaanakya/starting-my-python-adventure-97d5916ee84f">Starting My Python Adventure</a></p><h3>Tuples</h3><ul><li><strong>Ordering</strong>: Yes. Tuples maintain the order of elements.</li><li><strong>Mutability</strong>: Immutable. Once created, elements cannot be changed.</li><li><strong>Hashing</strong>: Hashable. Tuples can be used as keys in dictionaries if they contain hashable elements.</li><li><strong>Indexing</strong>: Supports indexing like lists.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7fa7e2fd65f6849b0b874ad13f242e2/href">https://medium.com/media/c7fa7e2fd65f6849b0b874ad13f242e2/href</a></iframe><p>To read more about tuples:</p><p><a href="https://medium.com/@chaanakya/exploring-python-tuples-ordered-and-immutable-cbcca87a6d34">Exploring Python Tuples: Ordered and Immutable</a></p><h3>Sets</h3><ul><li><strong>Ordering</strong>: No. Sets do not maintain any specific order for elements.</li><li><strong>Mutability</strong>: Mutable. You can add or remove elements.</li><li><strong>Hashing</strong>: Set elements must be hashable.</li><li><strong>Indexing</strong>: Does not support indexing.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6d7bfda750ba7b456353176f63d5c0e/href">https://medium.com/media/b6d7bfda750ba7b456353176f63d5c0e/href</a></iframe><p>To read more about set data structure:</p><p><a href="https://medium.com/@chaanakya/understanding-pythons-set-data-structure-a-comprehensive-guide-c5f63ba0c371">Understanding Python’s Set Data Structure: A Comprehensive Guide</a></p><h3>Dictionaries</h3><ul><li><strong>Ordering</strong>: Yes (as of Python 3.7). Dictionaries maintain the order of elements.</li><li><strong>Mutability</strong>: Mutable. You can change, add, or remove key-value pairs.</li><li><strong>Hashing</strong>: Keys must be hashable, but dictionaries themselves are not hashable.</li><li><strong>Indexing</strong>: Supports indexing via keys.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04de015cc29eee63a92cb37e92cd5c04/href">https://medium.com/media/04de015cc29eee63a92cb37e92cd5c04/href</a></iframe><p>To read more about dictionary:</p><p><a href="https://medium.com/@chaanakya/understanding-python-dictionary-a-comprehensive-guide-ab078bd116b3">Understanding Python Dictionary: A Comprehensive Guide</a></p><h3>How These Data Structures Work Internally</h3><h4>Lists</h4><p>Lists in Python are implemented as dynamic arrays. They store references to their elements, and the list can grow or shrink dynamically as you add or remove items.</p><h4>Tuples</h4><p>Tuples are implemented similarly to lists but are immutable. Once a tuple is created, its size and elements cannot be altered. They are often used for fixed collections of items.</p><h4>Sets</h4><p>Sets are implemented using hash tables. This allows sets to store unique elements and perform operations like checking for membership quickly. Hash tables provide rapid insertion, deletion, and membership checks.</p><h4>Dictionaries</h4><p>Dictionaries are implemented as hash tables, similar to sets, but store key-value pairs. Each key in a hash table points to a specific value. Keys must be hashable, and the dictionary can grow or shrink as items are added or removed.</p><h3>Conclusion</h3><p>Understanding the characteristics and performance of Python’s built-in data structures will allow you to select the right one for your programming task. Each structure has unique properties that make them suitable for different types of tasks, optimizing your code’s performance and efficiency.</p><p>Below is a summary table to recap their main differences:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e5323a0788eedb4e63921ad0a1bf102/href">https://medium.com/media/3e5323a0788eedb4e63921ad0a1bf102/href</a></iframe><p><a href="https://medium.com/@chaanakya/subscribe">Get an email whenever Chaanakya publishes.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d608af376de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python’s Set Data Structure: A Comprehensive Guide]]></title>
            <link>https://medium.com/@chaanakya/understanding-pythons-set-data-structure-a-comprehensive-guide-c5f63ba0c371?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f63ba0c371</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 16:44:39 GMT</pubDate>
            <atom:updated>2025-04-22T16:44:39.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is a versatile programming language that offers a variety of built-in data structures to simplify coding tasks. Among these, the <strong>set</strong> data structure stands out for its ability to handle unique elements efficiently. In this article, we will dive deep into Python sets, exploring their concepts, methods, time complexities and internal workings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MalEvFSjkMeBdEHQiGCUBA.png" /></figure><h3>What is a Set in Python?</h3><p>A <strong>set</strong> in Python is an <strong>unordered collection of unique and mutable elements</strong>. Unlike lists or tuples, sets do not allow duplicate values, making them ideal for scenarios where uniqueness is a priority. Sets are mutable, meaning you can add or remove elements after their creation.</p><h4>Key Characteristics of Sets:</h4><ol><li><strong>Unordered</strong>: The elements in a set do not maintain any specific order.</li><li><strong>Unique</strong>: Duplicate elements are not allowed in a set. Set is ensured to always have unique elements</li><li><strong>Immutable Elements</strong>: Elements within a set must be immutable (e.g., numbers, strings, tuples).</li></ol><h3>How to Create a Set in Python</h3><p>You can create a set using curly braces {} or the set() constructor.</p><pre># Using curly braces<br>my_set = {1, 2, 3, 4}<br><br># Using the set() constructor<br>another_set = set([1, 2, 3, 4])<br><br># Empty set (use set(), not {})<br>empty_set = set()</pre><h4>Points to note</h4><ol><li><strong>Do not use</strong><strong>{}to initialize an empty set.</strong> It will initialize a dictionary, not set.</li></ol><pre>my_set = {};<br>type(my_set) #Output: dict</pre><p>2. <strong>You cannot add mutable elements to a set.</strong></p><pre>my_set = {1, [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]}<br># TypeError: unhashable type: &#39;list&#39;</pre><p>The elements in a set can only be immutable. Python will throw an error if you try to add mutable elements.</p><h3>Methods of Python Sets with Examples</h3><p>Python sets come with a rich set of methods for performing various operations. Below is a detailed explanation of each method, along with examples.</p><h4>1. add()</h4><p>Adds a single element to the set.</p><pre>my_set = {1, 2, 3}<br>my_set.add(4)<br>print(my_set)  # Output: {1, 2, 3, 4}</pre><h4>2. update()</h4><p>Adds multiple elements to the set. <strong>This updates the given set with the new values</strong></p><pre>my_set = {1, 2, 3}<br>my_set.update([4, 5, 6])<br><br>print(my_set)  # Output: {1, 2, 3, 4, 5, 6}</pre><pre>my_set = {1, 2, 3}<br>my_set.update({4, 5, 6})<br>print(my_set) # Output: {1, 2, 3, 4, 5, 6}</pre><h4>3. remove()</h4><p>Removes a specific element from the set. Raises a KeyError if the element is not found.</p><pre>my_set = {1, 2, 3}<br>my_set.remove(2)<br>print(my_set)<br><br># Output: {1, 3}</pre><p>The method will throw an error if the element if not present.</p><pre>my_set = {1, 2, 3}<br>my_set.remove(4)<br>  <br># KeyError: 4</pre><h4>4. discard()</h4><p>Removes a specific element from the set without raising an error if the element is not found.</p><pre>my_set = {1, 2, 3}<br>my_set.discard(4)  # No error<br>print(my_set)<br><br># Output: {1, 2, 3}</pre><h4>5. pop()</h4><p>Removes and returns an arbitrary element from the set.</p><pre>my_set = {1, 2, 3}<br>removed_element = my_set.pop()<br><br>print(removed_element)  <br># Output: (arbitrary element, e.g., 1)<br><br>print(my_set)  <br># Output: Remaining elements</pre><h4>6. clear()</h4><p>Removes all elements from the set.</p><pre>my_set = {1, 2, 3}<br>my_set.clear()<br>print(my_set)  <br><br># Output: set()</pre><h4>7. union()</h4><p>Returns a new set containing all elements from both sets. <strong>The existing sets will not be modified.</strong></p><pre>set1 = {1, 2, 3}<br>set2 = {3, 4, 5}<br>result = set1.union(set2)<br><br>print(set1)  # Output: {1, 2, 3}<br>print(set2)  # Output: {3, 4, 5}<br>print(result)  # Output: {1, 2, 3, 4, 5}</pre><h4>8. intersection()</h4><p>Returns a new set containing elements common to both sets. <strong>The existing sets will not be modified.</strong></p><pre>set1 = {1, 2, 3}<br>set2 = {3, 4, 5}<br>result = set1.intersection(set2)<br>print(result)  # Output: {3}</pre><h4>9. difference()</h4><p>Returns a new set containing elements in the first set but not in the second. <strong>The existing sets will not be modified.</strong></p><pre>set1 = {1, 2, 3}<br>set2 = {3, 4, 5}<br>result = set1.difference(set2)<br>print(result)  # Output: {1, 2}</pre><h4>10. symmetric_difference()</h4><p>Returns a new set containing elements in either set but not in both. <strong>The existing sets will not be modified.</strong></p><pre>set1 = {1, 2, 3}<br>set2 = {3, 4, 5}<br>result = set1.symmetric_difference(set2)<br><br>print(result)  <br># 3 is common in both the lists. so it will not be present in the output<br># Output: {1, 2, 4, 5}.</pre><h4>11. issubset()</h4><p>Checks if the set is a subset of another set.</p><pre>set1 = {1, 2}<br>set2 = {1, 2, 3}<br>print(set1.issubset(set2))  <br># Output: True</pre><h4>12. issuperset()</h4><p>Checks if the set is a superset of another set.</p><pre>set1 = {1, 2, 3}<br>set2 = {1, 2}<br>print(set1.issuperset(set2))  <br># Output: True</pre><h4>13. isdisjoint()</h4><p>Checks if two sets have no elements in common.</p><pre>set1 = {1, 2}<br>set2 = {3, 4}<br>print(set1.isdisjoint(set2))  <br># Output: True</pre><h3>Time Complexities of Set Methods</h3><p>Below is a table summarizing the time complexities of set operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af1744746493dab69b1cd1f9a89b2a5a/href">https://medium.com/media/af1744746493dab69b1cd1f9a89b2a5a/href</a></iframe><h3>Why Mutable elements cannot be added in set</h3><p>In Python, elements of a set need to be immutable because of how sets are implemented. Sets use a hash table to store their elements. Let’s break this down:</p><p>When an element is added to a set, Python applies a hash function to the element, producing a hash value. This hash value is used to determine the index in the hash table where the element should be stored.</p><p>Each element must have a unique hash value to ensure fast lookups, insertions, and deletions.</p><p>If a mutable object were allowed as an element of a set, any mutation to the object would potentially change its hash value, leading to errors such as <em>element not found</em> or <em>duplicate entries</em>, which contradicts the set property of having distinct elements.</p><h3>Practical Examples with Solutions</h3><h4>Example 1: Find Unique Elements in a List</h4><pre>numbers = [1, 2, 2, 3, 4, 4, 5]<br>unique_numbers = set(numbers)<br>print(unique_numbers)  # Output: {1, 2, 3, 4, 5}</pre><h4>Example 2: Check Common Elements Between Two Lists</h4><pre>list1 = [1, 2, 3]<br>list2 = [3, 4, 5]<br>common_elements = set(list1).intersection(list2)<br>print(common_elements)  # Output: {3}</pre><h4>Example 3: Remove Duplicates and Sort</h4><pre>numbers = [4, 2, 1, 3, 2, 4]<br>unique_sorted = sorted(set(numbers))<br>print(unique_sorted)  # Output: [1, 2, 3, 4]</pre><h3>How Sets Work Internally in Python</h3><p>Internally, Python sets are implemented using <strong>hash tables</strong>. Each element in the set is hashed to determine its position in the table. This hashing mechanism ensures that operations like add, remove, and lookup are performed in constant time (O(1)).</p><h4>Key Points:</h4><ul><li>The hash table allows fast access to elements.</li><li>Hash collisions are handled using chaining or open addressing.</li><li>Sets require elements to be hashable and immutable.</li></ul><h3>Comparison: Python Sets vs Java HashSet</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f6c9dd6fe17f7107a3e300eb5c4e88a/href">https://medium.com/media/2f6c9dd6fe17f7107a3e300eb5c4e88a/href</a></iframe><h3>Conclusion</h3><p>Python sets are a powerful and efficient data structure for handling unique elements. With their rich set of methods and fast operations, they are ideal for tasks like deduplication, membership testing, and set operations.</p><p><a href="https://medium.com/@chaanakya/subscribe">Get an email whenever Chaanakya publishes.</a></p><p>If you want to understand the other data structures in python, you can read about them here.</p><ul><li><a href="https://medium.com/@chaanakya/starting-my-python-adventure-97d5916ee84f">Starting My Python Adventure</a></li><li><a href="https://medium.com/@chaanakya/exploring-python-tuples-ordered-and-immutable-cbcca87a6d34">Exploring Python Tuples: Ordered and Immutable</a></li><li><a href="https://medium.com/@chaanakya/understanding-python-dictionary-a-comprehensive-guide-ab078bd116b3">Understanding Python Dictionary: A Comprehensive Guide</a></li></ul><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f63ba0c371" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python Dictionary: A Comprehensive Guide]]></title>
            <link>https://medium.com/@chaanakya/understanding-python-dictionary-a-comprehensive-guide-ab078bd116b3?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab078bd116b3</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-data-structures]]></category>
            <category><![CDATA[dictionary-in-python]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 10:22:34 GMT</pubDate>
            <atom:updated>2025-04-21T10:22:34.865Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore Python dictionaries in depth, including their concepts, operations, real-world applications, complexity analysis, and comparisons with Java data structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fazaCKZgbZUbjrCR6_WcaA.png" /></figure><h3>What is a Python Dictionary?</h3><p>A dictionary in Python is an <strong>unordered, mutable, and indexed collection of key-value pairs.</strong> It allows you to store data in a way that is easy to retrieve using unique keys.</p><h4>Unordered: No Fixed Sequence</h4><p>Unlike lists or tuples, dictionaries in Python are unordered. This means that the items in a dictionary do not have a fixed sequence, and their order may not be preserved. When you access or iterate over a dictionary, the order of the key-value pairs may differ from the order in which they were added.</p><h4>Mutable: Changeable and Dynamic</h4><p>Python dictionaries are mutable, meaning you can change their contents after they are created. You can add new key-value pairs, update existing values, or remove items from the dictionary.</p><h4>Indexed: Accessing Data by Keys</h4><p>Dictionaries are indexed, meaning you can access values directly using their keys. This is different from lists, where you access elements by their position (index). In a dictionary, the key acts as the index.</p><h4>Key Features of Python Dictionaries:</h4><ul><li><strong>Keys </strong>must be immutable (e.g., strings, numbers, tuples).</li><li><strong>Values </strong>can be of any data type.</li><li>Maintains insertion order (since Python 3.7+).</li></ul><h3>How to Create a Dictionary in Python</h3><p>Python provides multiple ways to create dictionaries. Here are the most common methods:</p><h4>1. Using Curly Braces {}:</h4><p>The simplest way to create a dictionary is by specifying key-value pairs inside curly braces.</p><pre>my_dict = {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25, &quot;city&quot;: &quot;New York&quot;}<br>print(my_dict) <br># Output: {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 25, &#39;city&#39;: &#39;New York&#39;}Creating an Empty Dictionary:</pre><p>You can create an empty dictionary and populate it later.</p><pre>empty_dict = {}<br>empty_dict[&quot;name&quot;] = &quot;Alice&quot;<br>print(empty_dict) <br># Output: {&#39;name&#39;: &#39;Alice&#39;}</pre><h4>2. Using the dict() Constructor:</h4><p>You can use the dict() constructor to create a dictionary.</p><pre>my_dict = dict(name=&quot;Alice&quot;, age=25, city=&quot;New York&quot;)<br>print(my_dict) <br># Output: {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 25, &#39;city&#39;: &#39;New York&#39;}</pre><h3>Accessing Elements from a Dictionary</h3><p>Python provides several methods to access elements from a dictionary. Let’s explore these methods in detail.</p><h4>1. Accessing Values Using Keys</h4><p>The most straightforward way to access a value in a dictionary is by using its key. You can use square brackets ([]) to retrieve the value associated with a specific key.</p><pre>person = {<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;city&quot;: &quot;New York&quot;<br>}<br><br># Accessing the value of the key &quot;name&quot;<br>print(person[&quot;name&quot;])  <br># Output: Alice<br><br># Accessing the value of the key &quot;age&quot;<br>print(person[&quot;age&quot;])  <br># Output: 30</pre><p><strong>KeyError Exception: </strong>If you try to access a key that doesn’t exist in the dictionary, Python will raise a KeyError. To avoid this, you can use the in operator to check if a key exists before accessing it.</p><pre>if &quot;country&quot; in person:<br>    print(person[&quot;country&quot;])<br>else:<br>    print(&quot;Key not found!&quot;)  # Output: Key not found!</pre><h4>2. Using the get() Method</h4><p>The get() method is a safer way to access dictionary values. It allows you to specify a default value that will be returned if the key doesn’t exist, preventing a KeyError.</p><pre>person = {<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;city&quot;: &quot;New York&quot;<br>}<br><br># Using get() to access a key<br>print(person.get(&quot;name&quot;))  <br># Output: Alice<br><br># Accessing a non-existent key with a default value<br>print(person.get(&quot;country&quot;, &quot;Unknown&quot;))  <br># Output: Unknown</pre><h4>3. Accessing All Keys and Values</h4><p>Sometimes, you may need to access all the keys or values in a dictionary. Python provides two built-in methods for this purpose: keys() and values().</p><p><strong>Accessing Keys</strong></p><p>The keys() method returns a view object containing all the keys in the dictionary.</p><pre>person = {<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;city&quot;: &quot;New York&quot;<br>}<br><br>print(person.keys())  <br># Output: dict_keys([&#39;name&#39;, &#39;age&#39;, &#39;city&#39;])</pre><p><strong>Accessing Values</strong></p><p>The values() method returns a view object containing all the values in the dictionary.</p><pre>print(person.values())  <br># Output: dict_values([&#39;Alice&#39;, 30, &#39;New York&#39;])</pre><h4>4. Accessing Key-Value Pairs Using items()</h4><p>The items() method returns a view object containing key-value pairs as tuples. This is particularly useful when you need to iterate over both keys and values.</p><pre>person = {<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;city&quot;: &quot;New York&quot;<br>}<br><br>for key, value in person.items():<br>    print(f&quot;{key}: {value}&quot;)<br><br># Output:<br># name: Alice<br># age: 30<br># city: New York</pre><h4>5. Iterating Over a Dictionary</h4><p>You can use a for loop to iterate over a dictionary. By default, the loop iterates over the keys. To access values, you can use the key within the loop.</p><pre>person = {<br>    &quot;name&quot;: &quot;Alice&quot;,<br>    &quot;age&quot;: 30,<br>    &quot;city&quot;: &quot;New York&quot;<br>}<br><br># Iterating over keys<br>for key in person:<br>    print(key)<br># Output:<br># name<br># age<br># city<br><br># Iterating over values<br>for key in person:<br>    print(person[key])<br># Output:<br># Alice<br># 30<br># New York</pre><h3>Dictionary Methods Explained</h3><p>Python dictionaries come with several built-in methods. I have explain most of the methods related to accessing elements above. Here’s a table summarizing all the methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d9732185f77b5f3f7b24ea276bb3a10/href">https://medium.com/media/1d9732185f77b5f3f7b24ea276bb3a10/href</a></iframe><h3>Complexity Analysis of Dictionary Operations</h3><p>Understanding the time complexity of dictionary operations is crucial for optimizing your code. Below is a table summarizing the complexity of common dictionary operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1e8590e32ca381160ae75fd976abb19/href">https://medium.com/media/d1e8590e32ca381160ae75fd976abb19/href</a></iframe><h3>Real-World Applications of Dictionaries</h3><p>Dictionaries are widely used in real-world scenarios due to their efficiency and flexibility. Here are some examples:</p><h4>Example 1: Storing User Profiles</h4><pre>user_profiles = {<br> &quot;alice&quot;: {&quot;age&quot;: 25, &quot;email&quot;: &quot;alice@example.com&quot;},<br> &quot;bob&quot;: {&quot;age&quot;: 30, &quot;email&quot;: &quot;bob@example.com&quot;}<br>}<br>print(user_profiles[&quot;alice&quot;][&quot;email&quot;])<br><br># Output: alice@example.com</pre><h4>Example 2: Counting Word Frequencies</h4><pre>text = &quot;hello world hello python&quot;<br>word_count = {}<br>for word in text.split():<br> word_count[word] = word_count.get(word, 0) + 1<br>print(word_count)<br><br># Output: {&#39;hello&#39;: 2, &#39;world&#39;: 1, &#39;python&#39;: 1}</pre><h3>Comparison with Java HashMap</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/957c81c23a5f01a7ce71ce15a1a1ebb7/href">https://medium.com/media/957c81c23a5f01a7ce71ce15a1a1ebb7/href</a></iframe><h3>Corner Cases and Best Practices</h3><h4>1. Avoiding KeyError</h4><p>Always check if a key exists using the in operator or the get() method to prevent runtime errors.</p><h4>2. Using Meaningful Keys</h4><p>Choose descriptive keys to make your dictionary easier to understand and maintain.</p><h4>3. Iterating Efficiently</h4><p>Use items() when you need both keys and values during iteration, as it’s more efficient than accessing values separately.</p><h4><strong>4. Mutable Keys</strong>:</h4><p>Using mutable types (e.g., lists) as keys raises a TypeError. python my_dict = {[1, 2]: &quot;value&quot;} # Raises TypeError</p><h3>Practice Questions</h3><ol><li>Write a Python program to merge two dictionaries.</li><li>Create a dictionary to count the frequency of characters in a string.</li><li>Implement a function that removes all keys with None values from a dictionary.</li><li>Write a program to find the key with the maximum value in a dictionary. — -</li></ol><h3>Conclusion</h3><p>Python dictionaries are a powerful tool for managing key-value pairs efficiently. By understanding their operations, complexities, and corner cases, you can leverage dictionaries to solve a wide range of problems.</p><p><a href="https://medium.com/@chaanakya/subscribe">Get an email whenever Chaanakya publishes.</a></p><p>I have previously written articles on lists and tuples. You can read about them here.</p><ul><li><a href="https://medium.com/@chaanakya/starting-my-python-adventure-97d5916ee84f">Starting My Python Adventure</a></li><li><a href="https://medium.com/@chaanakya/exploring-python-tuples-ordered-and-immutable-cbcca87a6d34">Exploring Python Tuples: Ordered and Immutable</a></li></ul><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab078bd116b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Python Tuples: Ordered and Immutable]]></title>
            <link>https://medium.com/@chaanakya/exploring-python-tuples-ordered-and-immutable-cbcca87a6d34?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbcca87a6d34</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python-data-structures]]></category>
            <category><![CDATA[tuples]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tuples-in-python]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 03:56:57 GMT</pubDate>
            <atom:updated>2025-04-18T03:56:57.928Z</atom:updated>
            <content:encoded><![CDATA[<p>This article talks about tuples in python and how to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPsyFmZZKXwm6eWAfjKY4Q.png" /></figure><p>At its core, a tuple is an <strong>ordered</strong>, <strong>immutable</strong> collection of elements.</p><p>Understanding the concepts of ordered and immutable is crucial when working with data structures like tuples in Python. Let’s explore what these terms mean:</p><h4>Ordered</h4><p>When we say a data structure is <em>ordered</em>, it means that the elements are arranged in a specific sequence, and you can access these elements based on their position or index.<br>For example, in a tuple (10, 20, 30), the element at index 0 is 10 and the element at index 2 is 30.</p><p>In Python, tuples and lists are examples of ordered data structures. Set is an unordered data structure, meaning you can’t access the elements using index and you have no control on the order.</p><h4>Immutable</h4><p>Immutability refers to the characteristic of certain data structures where the elements inside them cannot be altered after the structure has been created.</p><ul><li><strong>No Modification</strong>: You cannot add, remove, or change elements in an immutable data structure like a tuple. If you need a modified version, you typically create a new tuple with the desired changes.</li><li><strong>Safety</strong>: Immutability can enhance safety because once the data structure is initialized, its content is guaranteed not to be inadvertently changed, which is particularly useful in concurrent scenarios or when protecting critical data.</li></ul><h3>Creating Tuples</h3><p>Tuples can be defined using parentheses or the tuple() constructor:</p><pre># Using parentheses  <br>my_tuple = (1, &#39;Python&#39;, 3.0)  <br>  <br># Using the tuple() function  <br>another_tuple = tuple([10, 20, 30])</pre><h4>Edge case:</h4><p>Single value enclosed in a parentheses is not a tuple. For example:</p><pre># Not a tuple  <br>not_a_tuple = (5)  <br>print(type(not_a_tuple))  # Output: &lt;class &#39;int&#39;&gt;</pre><p>This is because ( ) is used to calculate arithmetic expressions or to logically group conditions. If we just wrap a single element in parentheses, python will assume its just an expression.</p><p>To correctly define a one-element tuple, we need to add a trailing comma.</p><pre># Correctly defining a single-element tuple  <br>single_element_tuple = (5,)  <br>print(type(single_element_tuple))  # Output: &lt;class &#39;tuple&#39;&gt;</pre><h3>Accessing elements</h3><p>To access elements, we can use the <em>tuple[index]</em> notation.</p><pre>my_tuple = (1, 2, 3, 4)<br>my_tuple[2] # 2nd index =&gt; 3<br>my_tuple[3] # 3rd index =&gt; 4<br>my_tuple[-1] # last index =&gt; -1<br>my_tuple[-2] # second last index =&gt; -3</pre><h4><strong>Edge Case: </strong>IndexError</h4><p>Throws an IndexError if index is out of range.</p><pre>my_tuple = (1, 2, 3, 4)<br>my_tuple[10]<br><br># IndexError: tuple index out of range</pre><p>Since tuple is immutable, you cannot update a value once it is initialized.</p><pre>my_tuple = (1, 2, 3, 4)<br>my_tuple[0] = &quot;zero&quot;<br><br># TypeError: &#39;tuple&#39; object does not support item assignment</pre><h3>Tuple Methods</h3><h4><strong>count(value)</strong>:</h4><p>Returns the number of occurrences of a specific value.</p><pre>example_tuple = (1, 2, 2, 3)<br>count_of_2 = example_tuple.count(2)<br># Output: 2</pre><h4><strong>index(value, start=0, end=len(tuple))</strong></h4><p>Finds the first index of a value.</p><pre>example_tuple = (1, 2, 2, 3)<br>index_of_2 = example_tuple.index(2) <br># Output: 1</pre><p>you can use optional start and end parameters to search within a given index range [start, end), including start index and excluding end index.</p><pre>my_tuple = (1, 2, 3, 4, 2, 5, 5, 5, 5, 5)<br>my_tuple.index(2, 4, 9) <br># search for element 2 between 4th and 9th index<br># Output: 4<br><br><br>my_tuple = (1, 2, 3, 4, 2, 5, 5, 2, 5, 5, 5)<br>my_tuple.index(2, 5, 9)<br># search for element 2 between 5th and 9th index<br># Output: 7</pre><p><strong>Edge case: ValueError</strong></p><p>Python will throw ValueError if the element is not found in the tuple, so ensure the item exists.</p><pre>my_tuple = (1, 2, 3, 4)<br>my_tuple.index(10)<br><br># ValueError: tuple.index(x): x not in tuple</pre><h3>Points to keep in mind</h3><ul><li><strong>Accessing Index</strong>: Accessing an index outside the range will raise an IndexError. Always check the length before accessing.</li><li><strong>Immutable</strong>: Tuples are immutable. You cannot change the values once initialized.</li></ul><p><a href="https://medium.com/@chaanakya/subscribe">Get an email whenever Chaanakya publishes.</a></p><p>That’s it for now. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbcca87a6d34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create String in python]]></title>
            <link>https://medium.com/@chaanakya/how-to-create-string-in-python-ccd83b3e6d5f?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccd83b3e6d5f</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[python-data-type]]></category>
            <category><![CDATA[data-types-in-python]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 08:35:34 GMT</pubDate>
            <atom:updated>2025-04-17T08:35:34.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Different ways to create string in python</p><p>In Python, strings are a fundamental data type used to represent text. They’re sequences of characters and are immutable, meaning once a string is created, it cannot be changed.</p><p>Here’s how you can create strings in Python.</p><p>You can create strings in python using <strong>single quotes, double quotes or triple quotes.</strong></p><pre>str1 = &#39;Hello, World!&#39; # using single quotes</pre><p>But if your string needs to have to single quote in it too, then you need to escape it. If not, it will throw a syntax error.</p><pre>str1 = &#39;I\&#39;m looking for help&#39; # using single quotes with escaping.</pre><p>Or you can use double quotes to create the string without the need to escape.</p><pre>str1 = &quot;I&#39;m looking for help&quot; # using double quotes</pre><p>If your string needs to have a double quote inside it, then you can use single quotes to create the string so that you don’t need to escape double quotes.</p><pre>str1 = &#39;He said &quot;How are you&quot;&#39; # using single quotes</pre><p>If your string needs to have both single and double quotes, then you can use triple quotes to initialize the string.</p><pre>str1 = &#39;&#39;&#39;I asked him &quot;how are you&quot;. he said &quot;I&#39;m fine&quot;.&#39;&#39;&#39; #using triple single quotes</pre><pre>str1 = &quot;&quot;&quot;I asked him &quot;how are you&quot;. he said &quot;I&#39;m fine&quot;.&quot;&quot;&quot; #using triple double quotes</pre><p>You can also use triple quotes to create multi-line strings.</p><pre>str1 = &#39;&#39;&#39;I asked him &quot;how are you&quot;.<br>He said &quot;I&#39;m fine&quot;.&#39;&#39;&#39; #using triple single quotes</pre><h4>Formatted string literals (f-strings)</h4><p>f-strings provide a concise way to embed expressions inside string literals using curly braces {}. They are evaluated at runtime and can include any valid Python expression.</p><p><strong>Using f-strings</strong> with <strong>single quotes</strong></p><pre>name = &#39;chaanakya&#39;<br>str1 = f&#39;my name is &quot;{name}&quot;&#39; #f-strings with single quotes<br><br>#str1: &#39;my name is &quot;chaanakya&quot;&#39;</pre><p><strong>Using f-strings with double quotes</strong></p><pre>name = &#39;chaanakya&#39;<br>str1 = f&quot;my name is &#39;{name}&#39;&quot; #f-strings with single quotes<br><br>#str1: &quot;my name is &#39;chaanakya&#39;&quot;</pre><p><strong>Using f-strings with triple quotes</strong></p><pre>name = &#39;chaanakya&#39;<br>str1 = f&#39;&#39;&#39;I asked &#39;{name}&#39; &quot;how are you&quot;.<br>He said &quot;I&#39;m fine&quot;.&#39;&#39;&#39; #f-strings with single quotes<br><br>#str1: &#39;I asked \&#39;chaanakya\&#39; &quot;how are you&quot;.\nHe said &quot;I\&#39;m fine&quot;.&#39;</pre><p>In conclusion we can create strings using single, double and triple quotes. With triple quotes you can create complicated strings that involves new lines and quotes together. f-strings are powerful mechanism to include variables/expressions in strings in a clean and efficient manner.</p><p><a href="https://medium.com/@chaanakya/subscribe">Get an email whenever Chaanakya publishes.</a></p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccd83b3e6d5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Python Lists]]></title>
            <link>https://medium.com/@chaanakya/starting-my-python-adventure-97d5916ee84f?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/97d5916ee84f</guid>
            <category><![CDATA[python-data-structures]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 17:29:15 GMT</pubDate>
            <atom:updated>2025-04-23T02:59:23.109Z</atom:updated>
            <content:encoded><![CDATA[<p>I‘ve just started learning Python and I’m excited to share what I discover in a series of articles. Coming from a Java background, I’m eager to explore how Python handles things.</p><p>In this story, I look specifically at Python lists. I’ll walk you through the basics of lists, including how they work, the common methods you can use, and some practical examples.</p><p>Whether you’re new to programming or just new to Python, I hope you find this article helpful on your own coding journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJ2TlHqh0OzvvDd2l6Iecg.png" /><figcaption>generated using chatgpt</figcaption></figure><h3>Python Lists</h3><p>Python lists are ordered, mutable collections of elements. Coming from a Java background, you can think of them as similar to Java’s ArrayList.</p><h3>Initializing a List</h3><p>Lists can be created using square brackets [].</p><pre># Using square brackets<br>lst1 = [1, 2, 3, &#39;a&#39;, &#39;b&#39;]<br>lst2 = []</pre><h3>Accessing elements</h3><ul><li>To access a list element we can use list[index] notation.</li><li><strong>Edge Case</strong>: Throws an IndexError if index is out of bounds.</li></ul><pre>lst = [1, 2, 3, &#39;a&#39;, &#39;b&#39;]<br>lst[1] # 1st index<br><br># output: 2</pre><pre>lst = [1, 2, 3, &#39;a&#39;, &#39;b&#39;]<br>lst[-1] #last index<br><br># output: &#39;b&#39;</pre><pre>lst = [1, 2, 3, &#39;a&#39;, &#39;b&#39;]<br>lst[7]<br><br># IndexError: list index out of range</pre><h3>Updating elements at index</h3><ul><li>To access a list element we can use list[index] = value notation.</li><li><strong>Edge Case</strong>: Throws an IndexError if index is out of bounds.</li></ul><pre>lst = [1, 2, 3, 4, 5]<br>lst[1] = &#39;two&#39;<br><br>#updated list: [1, &#39;two&#39;, 3, 4, 5]</pre><pre>lst = [1, 2, 3, 4, 5]<br>lst[-1] = &#39;five&#39;<br><br># updated list: [1, 2, 3, 4, &#39;five&#39;]</pre><pre>lst = [1, 2, 3, 4, 5]<br>lst[7] = &#39;seven&#39;<br><br># IndexError: list assignment index out of range</pre><h3>Common List Methods</h3><h3>1. append(x)</h3><ul><li>Adds an item, x, to the end of the list.</li></ul><pre>lst = [1, 2, 3]<br>lst.append(4)<br><br># updated list: [1, 2, 3, 4]</pre><h3>2. extend(iterable)</h3><ul><li>Extends the list by appending elements from an iterable like list</li></ul><pre>lst = [1, 2, 3]<br>lst.extend([4, 5, 6])<br><br># updated list: [1, 2, 3, 4, 5, 6]</pre><h3>3. insert(i, x)</h3><ul><li>inserts an element at a given index</li><li>if index is 0, it will add at the first index</li><li>if index &gt;= size, it will add at the end. it wont throw index out of bounds exception like in java.</li></ul><pre>lst = [1, 3, 4]<br>lst.insert(1, 2)<br><br># updated list: [1, 2, 3, 4]</pre><pre>lst = []<br>lst.insert(0, 1)<br><br># updated list: [1]</pre><pre>lst = [1,2]<br>lst.insert(10, 3)<br><br># updated list: [1, 2, 3]</pre><h3>4. remove(x)</h3><ul><li>Removes the first occurrence of a value.</li><li><strong>Edge Case</strong>: Raises ValueError if the item is not found, so ensure the item exists.</li></ul><pre>lst = [1, 2, 3, 2]<br>lst.remove(2)<br><br># updated list: [1, 3, 2]</pre><pre>lst = [1, 2, 3,]<br>lst.remove(4)<br><br># ValueError: list.remove(x): x not in list</pre><h3>5. pop([i])</h3><ul><li>Removes and returns the item at the given position</li><li>Removes the last item if no index is specified.</li><li>Removes from last if negative index is given</li><li>-1 indicates last element. -2 indicates second last and so on.</li></ul><pre>lst = [1, 2, 3]<br>popped = lst.pop() #pops last element<br>print(lst, popped)<br><br># updated list : [1, 2] <br># popped: 3</pre><pre>lst = [1, 2, 3]<br>popped = lst.pop(1)<br>print(lst, popped)<br><br># updated list : [1, 3] <br># popped: 2</pre><pre>lst = [1, 2, 3]<br>popped = lst.pop(-1) # pops last index<br>print(lst, popped)<br><br># updated list : [1, 2] <br># popped: 3</pre><pre>lst = [1, 2, 3]<br>popped = lst.pop(-2) # pops second last index<br>print(lst, popped)<br><br># updated list : [1, 3] <br># popped: 2</pre><h3>6. index(x)</h3><ul><li>Returns the index of the first occurrence of a value.</li><li><strong>Edge Case</strong>: Raises ValueError if the item is not found, so ensure the item exists.</li></ul><pre>lst = [1, 2, 3]<br>idx = lst.index(2)<br><br># idx: 1</pre><pre>lst = [1, 2, 3]<br>idx = lst.index(4)<br><br># ValueError: 4 is not in list</pre><h3>7. count(x)</h3><ul><li>Returns the number of times a value appears in the list.</li></ul><pre>lst = [1, 1, 2, 1]<br>cnt = lst.count(1) # 1 is present 3 times<br><br># cnt: 3</pre><pre>lst = [1, 1, 2, 1]<br>cnt = lst.count(4) # 4 is not present in the list<br># cnt: 0</pre><h3>8. sort()</h3><ul><li>Sorts the list in place.</li></ul><pre>lst = [3, 1, 2]<br>lst.sort()  # List becomes [1, 2, 3]<br><br># updated list: [1, 2, 3]</pre><h3>9. reverse()</h3><ul><li>Reverses the elements of the list in place.</li></ul><pre>lst = [1, 2, 3]<br>lst.reverse()  # List becomes [3, 2, 1]<br><br># updated list: [3, 2, 1]</pre><h3>10. copy()</h3><ul><li>Returns a shallow copy of the list.</li></ul><pre>lst1 = [1, 2, 3]<br>lst2 = lst1.copy()<br><br># lst2: [1, 2, 3]</pre><h3>11. clear()</h3><ul><li>Removes all items from the list.</li></ul><pre>lst = [1, 2, 3]<br>lst.clear()  # List becomes []<br><br># updated list: []p</pre><h3>Points to keep in mind</h3><ul><li><strong>Accessing Index</strong>: Accessing an index outside the range will raise an IndexError. Always check the length before accessing.</li><li><strong>Mutability</strong>: Lists are mutable, so changes affect all references.</li></ul><p><a href="https://medium.com/@chaanakya/subscribe">Get an email whenever Chaanakya publishes.</a></p><p>That’s it for now. I will continue to document and share my Python learning journey.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97d5916ee84f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JUnit 5  Assertions]]></title>
            <link>https://medium.com/javarevisited/junit-5-assertions-5d360545e3a?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d360545e3a</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[junit-5]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 15:46:57 GMT</pubDate>
            <atom:updated>2023-01-20T15:46:57.133Z</atom:updated>
            <content:encoded><![CDATA[<h3>JUnit 5 Assertions</h3><h4>Different assertion methods that are available in JUnit 5</h4><p>Assertion methods in <a href="https://medium.com/javarevisited/5-best-junit-and-test-driven-development-books-for-java-developers-2d3fecb5c9ac">JUnit 5</a>:</p><ul><li>assertTrue</li><li>assertFalse</li><li>assertNull</li><li>assertNotNull</li><li>assertEquals</li><li>assertNotEquals</li><li>assertArrayEquals</li><li>assertIterableEquals</li><li>assertThrows</li><li>assertDoesNotThrow</li></ul><h4>assertTrue and assertFalse</h4><p>assertTrue validates that the argument is true and assertFalse validates that the argument is false. They throw AssertionFailedError otherwise.</p><figure><a href="https://javarevisited.blogspot.com/2021/04/junit-interview-questions-with-answers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDlo_7mHOyhCgDoOs2ZB6A.png" /></a></figure><h4>assertNull and assertNotNull</h4><p>assertNull validates that the argument is <em>null</em> and assertNotNull validates that the argument is not null. They throw AssertionFailedError otherwise.</p><figure><a href="https://www.java67.com/2018/02/5-free-eclipse-and-junit-online-courses-java-developers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlioWNPsStHyS50tBlDxkQ.png" /></a></figure><h4>assertEquals and assertNotEquals</h4><p>assertEquals validates that the arguments are equal and assertNotEquals validates that the arguments are not equal. They throw AssertionFailedError otherwise.</p><figure><a href="https://javarevisited.blogspot.com/2012/08/best-practices-to-write-junit-test.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1oAWksk2jwPOkAEmakpYA.png" /></a></figure><h4><strong>assertSame</strong></h4><p>Validates that the arguments point to the same object (same reference). Check out <a href="https://medium.com/javarevisited/assertequals-vs-assertsame-911103bb57be">this article</a> for the difference between assertEquals and assertSame.</p><h4><strong>assertArrayEquals</strong></h4><p>Validates that the arrays are deeply equal.</p><p>It basically loops over the elements and calls the equals() method for the elements at every index. If the array is of primitive types, then it directly uses the equality operator (==).</p><p>If the element is an array (in case of 2D array), then it loops over those elements as well and repeats the process.</p><figure><a href="https://medium.com/javarevisited/5-courses-to-learn-junit-and-mockito-in-2019-best-of-lot-f217d8b93688"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7xL1u04cgOZXjtminPeLA.png" /></a></figure><h4>assertIterableEquals</h4><p>Validates that two iterable collections are equal. Throws AssertionFailedError if the contents differ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHsjzy5JjZKqXJP2HVxFNg.png" /></figure><h4>assertThrows</h4><p>assertThrows can be used to assert exceptions thrown by the method under test.</p><p><strong>Main parameters:</strong></p><ol><li>The exception type that is expected to be thrown.</li><li>An executable object that invokes the method/functionality under test.</li></ol><p>The below example is to test that the code throws IndexOutOfBoundsException.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFYzy2FOoKQjtIfjU_XHUA.png" /></figure><p>We can also validate the state that is exposed by the exception object. The assertThrows method returns the exception that is thrown and we can add validations on the exception object as well.</p><p>The below example extends the above example, but also verifies the error message from the exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9moDh9PImY8Gu0LiHR4OA.png" /></figure><h4>assertDoesNotThrow</h4><p>This can be used to validate that no exception is thrown by the functionality under test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDlHmK0CyjBudjiBuLDePQ.png" /></figure><p>You can also verify the output/return value of the code if no exception is thrown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bEwa8mbAoHnif_5_1llTA.png" /></figure><h4>assertAll</h4><p>The <em>assertAll</em> method can be used to group multiple assertions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4CqHOpRcCZcijPMU80Msg.png" /></figure><p>Check out <a href="https://medium.com/javarevisited/assertall-in-junit-5-177fa4ae4d28">this article</a> for more details on assertAll</p><p>Here’s the code for the above examples</p><p><a href="https://github.com/chaanakya123/junitexamples/blob/main/src/test/java/examples/assertions/Junit5Assertions.java">junitexamples/Junit5Assertions.java at main · chaanakya123/junitexamples</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ON5XKOz-O05Hg_luEiH5yQ.png" /></figure><h4>Related Articles</h4><ul><li><a href="https://medium.com/javarevisited/assertequals-vs-assertsame-911103bb57be">assertEquals vs assertSame</a></li><li><a href="https://medium.com/javarevisited/assertall-in-junit-5-177fa4ae4d28">assertAll in JUnit 5</a></li></ul><p>I hope you have learned something from the article. Feel free to ask any questions or share any comments you have about the article.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d360545e3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/junit-5-assertions-5d360545e3a">JUnit 5  Assertions</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[assertAll in JUnit 5]]></title>
            <link>https://medium.com/javarevisited/assertall-in-junit-5-177fa4ae4d28?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/177fa4ae4d28</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[junit-5]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 15:46:15 GMT</pubDate>
            <atom:updated>2023-01-18T15:46:15.910Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using the assertAll method vs asserting in separate statements</h4><p><strong>assertAll</strong> method is used to validate all the assertions passed to it.</p><p>Here’s what the official documentation says about the method:</p><blockquote><em>Asserts</em> that <em>all</em> supplied executables do not throw exceptions.</blockquote><blockquote>If any supplied <a href="https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/function/Executable.html">Executable</a> throws an exception (i.e., a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html?is-external=true">Throwable</a> or any subclass thereof), all remaining executables will still be executed, and all exceptions will be aggregated and reported in a <a href="https://ota4j-team.github.io/opentest4j/docs/1.0.0/api/org/opentest4j/MultipleFailuresError.html?is-external=true">MultipleFailuresError</a>. However, if an executable throws a <em>blacklisted</em> exception — for example, an <a href="https://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html">OutOfMemoryError </a>— execution will halt immediately, and the blacklisted exception will be rethrown <em>as is</em> but <em>masked</em> as an unchecked exception.</blockquote><blockquote>The supplied heading will be included in the message string for the <a href="https://ota4j-team.github.io/opentest4j/docs/1.0.0/api/org/opentest4j/MultipleFailuresError.html?is-external=true">MultipleFailuresError</a>.</blockquote><h4>Usage</h4><pre>@Test<br>void testAssertions() {<br>    assertAll(<br>        () -&gt; assertEquals(&quot;1&quot;, &quot;1&quot;),<br>        () -&gt; assertTrue(1 == 2),<br>        ......<br>    );<br>}</pre><h4>Using assertAll vs asserting separately</h4><p>The difference between passing assertions to this method vs asserting them in separate statements is that “the <strong>assertAll </strong>method<strong> </strong>executes all the assertions passed to it, even though some assertion fails”</p><pre>// Example of assertAll<br>@Test<br>void testAssertions() {<br>    assertAll(<br>        () -&gt; assertEquals(&quot;1&quot;, &quot;1&quot;),<br>        () -&gt; assertEquals(&quot;1&quot;, &quot;2&quot;),<br>        () -&gt; assertTrue(1 == 2)<br>    );<br>}<br><br><br>/*<br>Output:<br><br>org.opentest4j.MultipleFailuresError: Multiple Failures (2 failures)<br>  org.opentest4j.AssertionFailedError: expected: &lt;1&gt; but was: &lt;2&gt;<br>  org.opentest4j.AssertionFailedError: expected: &lt;true&gt; but was: &lt;false&gt;<br>*/</pre><p>If we write the <a href="https://javarevisited.blogspot.com/2012/01/what-is-assertion-in-java-java.html">assertions </a>in separate statements, then the test execution will end immediately whenever an assertion fails. The assertions that follow the failed assertion will not be executed.</p><pre>// Example of asserting separately<br>@Test<br>void testAssertions() {<br>    assertEquals(&quot;1&quot;, &quot;1&quot;);<br><br>    /*<br>    when the test fails here it throws an AssertionFailedError <br>    and the test fails.<br>    The below assertTrue will not be executed<br>    */<br>    assertEquals(&quot;1&quot;, &quot;2&quot;);<br>    assertTrue(1 == 2);<br>}<br><br>/*<br>Output: <br>org.opentest4j.AssertionFailedError: <br>Expected :1<br>Actual :2<br>*/</pre><p>So executing all assertions even in case of an assertion failure is an advantage that the <strong>assertAll</strong> method offers.</p><figure><a href="https://javarevisited.blogspot.com/2012/06/junit4-annotations-test-examples-and.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D19Kidgb2j0DKfF-yqJMfQ.png" /></a></figure><h4>Working</h4><p>Let’s check the code of the <em>assertAll</em> method to see how it works as mentioned.</p><pre>// code from JUnit 5<br><br>static void assertAll(String heading, Stream&lt;Executable&gt; executables) {<br>    Preconditions.notNull(executables, &quot;executables stream must not be null&quot;);<br>  <br>    List&lt;Throwable&gt; failures = executables //<br>      .peek(executable -&gt; Preconditions.notNull(executable, &quot;individual executables must not be null&quot;))//<br>      .map(executable -&gt; {<br>       try {<br>        executable.execute();<br>        return null;<br>       }<br>       catch (Throwable t) {<br>        BlacklistedExceptions.rethrowIfBlacklisted(t);<br>        return t;<br>       }<br>      }) //<br>      .filter(Objects::nonNull) //<br>      .collect(Collectors.toList());<br>  <br>    if (!failures.isEmpty()) {<br>     MultipleFailuresError multipleFailuresError = new MultipleFailuresError(heading, failures);<br>     failures.forEach(multipleFailuresError::addSuppressed);<br>     throw multipleFailuresError;<br>    }<br> }</pre><p>Each <em>Executable</em> object/assertion is executed within a try-catch to make sure that the assertion failure is not immediately thrown. The mapper/transformation function <strong>returns null if the test passes, </strong>and<strong> returns throwable if the test fails.</strong></p><p>The stream of <em>Executable’s</em> is converted into a stream of <em>Throwable’s</em>. The non-null objects are filtered (the assertions that failed), and are collected into a list. The list is wrapped in a MultipleFailuresError and is thrown at the end collectively.</p><p>That’s all for now. Feel free to ask any questions or share any comments you have about the article. See you in the next article.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177fa4ae4d28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/assertall-in-junit-5-177fa4ae4d28">assertAll in JUnit 5</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[assertEquals vs assertSame]]></title>
            <link>https://medium.com/javarevisited/assertequals-vs-assertsame-911103bb57be?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/911103bb57be</guid>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 15:42:36 GMT</pubDate>
            <atom:updated>2023-01-16T15:42:36.671Z</atom:updated>
            <content:encoded><![CDATA[<h4>Difference between assertEquals and assertSame in JUnit</h4><figure><a href="https://javarevisited.blogspot.com/2012/06/junit4-annotations-test-examples-and.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODMX0zyiRV1PpvXGkrf8aw.png" /></a></figure><h4>assertEquals</h4><p>Asserts that the expected and actual objects are equal.</p><p>It <strong>uses the </strong><a href="https://javarevisited.blogspot.com/2015/01/why-override-equals-hashcode-or-tostring-java.html"><strong>equals() method</strong></a> to verify if objects are equal. For primitives, it uses the equality operator.</p><p>Below is the code from <a href="https://medium.com/javarevisited/5-courses-to-learn-junit-and-mockito-in-2019-best-of-lot-f217d8b93688">JUnit 5</a>:</p><pre>// code from Junit for objects<br>static boolean objectsAreEqual(Object obj1, Object obj2) {<br>  if (obj1 == null) {<br>      return obj2 == null;<br>  } else {<br>      return obj1.equals(obj2);<br>  }<br>}<br><br>// code from Junit for primitives<br>static void assertEquals(int expected, int actual, String message) {<br>  if (expected != actual) {<br>      AssertionUtils.failNotEqual(expected, actual, message);<br>  }<br>}</pre><h4>assertSame</h4><p>Asserts that the expected and actual refer to the same object.</p><p>It uses the equality operator to verify that both actual and expected are pointing to the same object.</p><p>Below is the code from <a href="https://javarevisited.blogspot.com/2021/04/junit-interview-questions-with-answers.html">JUnit 5</a>:</p><pre>static void assertSame(Object expected, Object actual, String message) {<br>  if (expected != actual) {<br>      failNotSame(expected, actual, message);<br>  }<br>}</pre><h4>Example</h4><pre>class TestAssertEqualsAndSame {<br><br> @Test<br> void testAssertEquals() {<br>  assertEquals(&quot;1&quot;, &quot;1&quot;); // assertion will pass<br>  assertEquals(&quot;1&quot;, new String(&quot;1&quot;)); // assertion will pass<br>  assertEquals(new String(&quot;1&quot;), new String(&quot;1&quot;)); // assertion will pass<br> }<br><br> @Test<br> void testAssertSame() {<br>  // assertion will pass<br>  assertSame(&quot;1&quot;, &quot;1&quot;); <br><br>  /* <br>    assertion will fail because the references of both objects are different.<br>    new String(&quot;&lt;your string&gt;&quot;) will create a new object<br>  */<br>  assertSame(&quot;1&quot;, new String(&quot;1&quot;));<br><br>  // assertion will fail because the references of both objects are different<br>  assertSame(new String(&quot;1&quot;), new String(&quot;1&quot;));<br> }<br>}</pre><p>Feel free to ask any questions or share any comments you have about the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=911103bb57be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/assertequals-vs-assertsame-911103bb57be">assertEquals vs assertSame</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Execution order of JUnit annotations]]></title>
            <link>https://medium.com/javarevisited/execution-order-of-junit-annotations-cda673cda470?source=rss-c928edcd3e1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cda673cda470</guid>
            <category><![CDATA[junit-5]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chaanakya]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 15:26:06 GMT</pubDate>
            <atom:updated>2023-01-12T15:26:06.349Z</atom:updated>
            <content:encoded><![CDATA[<h4>The article will help you in understanding the execution order of the methods that use the annotations provided by JUnit 5</h4><figure><a href="https://javarevisited.blogspot.com/2021/04/junit-interview-questions-with-answers.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqenSLhr2Z2Rd5E1E1fukw.png" /></a></figure><h4>Basic annotations in <a href="https://medium.com/javarevisited/5-courses-to-learn-junit-and-mockito-in-2019-best-of-lot-f217d8b93688">JUnit 5</a></h4><ul><li>BeforeEach</li><li>BeforeAll</li><li>AfterEach</li><li>AfterAll</li></ul><h4><strong>BeforeEach</strong></h4><p>The method annotated with <em>BeforeEach</em> executes before each test. We can have multiple BeforeEach methods, but the execution order is not guaranteed.</p><p>This is similar to <em>Before</em> annotation in JUnit 4.</p><h4>AfterEach</h4><p>The method annotated with <em>AfterEach</em> executes after each test. We can have multiple AfterEach methods, but the execution order is not guaranteed.</p><p>This is similar to <em>After</em> annotation in JUnit 4.</p><h4>BeforeAll</h4><p>The method annotated with <em>BeforeAll</em> executes once before all the tests. This method has to be static.</p><p>This is similar to <em>BeforeClass</em> annotation in JUnit 4.</p><h4>AfterAll</h4><p>The method annotated with AfterAll executes once after all the tests. This method has to be static.</p><p>This is similar to <a href="https://javarevisited.blogspot.com/2012/06/junit4-annotations-test-examples-and.html"><em>AfterClass</em> annotation in JUnit 4.</a></p><figure><a href="https://javarevisited.blogspot.com/2012/06/junit4-annotations-test-examples-and.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GgMTVPeUov-SUyLOZa9tA.jpeg" /></a></figure><h4><strong>Example</strong></h4><pre>// example test class<br>public class TestClass {<br> static {<br>  System.out.println(&quot;Static block of Test class&quot;);<br> }<br><br> public TestClass() {<br>  System.out.println(&quot;Constructor of Test class&quot;);<br> }<br><br> @BeforeAll<br> public static void beforeAll() {<br>  System.out.println(&quot;Before All in Test class&quot;);<br> }<br><br> @AfterAll<br> public static void afterAll() {<br>  System.out.println(&quot;After All in Test class&quot;);<br> }<br><br> @BeforeEach<br> public void beforeEach() {<br>  System.out.println(&quot;Before Each In Test class&quot;);<br> }<br><br> @AfterEach<br> public void afterEach() {<br>  System.out.println(&quot;After Each in Test class&quot;);<br> }<br><br> @Test<br> public void testOne() {<br>  System.out.println(&quot;Test 1 in Test class&quot;);<br> }<br>}<br><br>/*<br>Output:<br><br>Static block of Test class<br>Before All in Test class<br>Constructor of Test class<br>Before Each In Test class<br>Test 1 in Test class<br>After Each in Test class<br>After All in Test class<br>*/<br></pre><p>The order in which these methods run for a test execution:</p><figure><a href="https://javarevisited.blogspot.com/2018/09/junit-testing-tips-constructor-is-called-before-test-methods.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MbptFdav9kQuXr2oAe3BAQ.png" /></a></figure><h4><strong>The order in which the methods run when the test class extends a base class:</strong></h4><p>Although I’m not really inclined towards this approach, I’ve seen it being used to avoid code duplication for setup across multiple test classes.</p><p>The following example should help you understand the order in which these methods execute when inheritance comes into picture.</p><pre>public class ParentClass {<br> static {<br>  System.out.println(&quot;Static block of Parent class&quot;);<br> }<br><br> public ParentClass() {<br>  System.out.println(&quot;Constructor of Parent class&quot;);<br> }<br><br> @BeforeAll<br> public static void beforeAllInParent() {<br>  System.out.println(&quot;Before All in Parent class&quot;);<br> }<br><br> @AfterAll<br> public static void afterAllInParent() {<br>  System.out.println(&quot;After All in Parent class&quot;);<br> }<br><br> @BeforeEach<br> public void beforeEachInParent() {<br>  System.out.println(&quot;Before Each in Parent class&quot;);<br> }<br><br> @AfterEach<br> public void afterEachInParent() {<br>  System.out.println(&quot;After Each in Parent class&quot;);<br> }<br>}</pre><pre>public class TestClass extends ParentClass {<br> static {<br>  System.out.println(&quot;Static block of Test class&quot;);<br> }<br><br> public TestClass() {<br>  System.out.println(&quot;Constructor of Test class&quot;);<br> }<br><br> @BeforeAll<br> public static void beforeAll() {<br>  System.out.println(&quot;Before All in Test class&quot;);<br> }<br><br> @AfterAll<br> public static void afterAll() {<br>  System.out.println(&quot;After All in Test class&quot;);<br> }<br><br> @BeforeEach<br> public void beforeEach() {<br>  System.out.println(&quot;Before Each In Test class&quot;);<br> }<br><br> @AfterEach<br> public void afterEach() {<br>  System.out.println(&quot;After Each in Test class&quot;);<br> }<br><br> @Test<br> public void testOne() {<br>  System.out.println(&quot;Test 1 in Test class&quot;);<br> }<br>}<br><br>/*<br>Output:<br><br>Static block of Parent class<br>Before All in Parent class<br>Static block of Test class<br>Before All in Test class<br>Constructor of Parent class<br>Constructor of Test class<br>Before Each in Parent class<br>Before Each In Test class<br>Test 1 in Test class<br>After Each in Test class<br>After Each in Parent class<br>After All in Test class<br>After All in Parent class<br>*/<br></pre><p>The order in which these methods run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqenSLhr2Z2Rd5E1E1fukw.png" /></figure><p>That’s all for now. Feel free to drop any comments or questions you have.<br>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cda673cda470" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/execution-order-of-junit-annotations-cda673cda470">Execution order of JUnit annotations</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>