diff --git a/Python_basics.ipynb b/Python_basics.ipynb new file mode 100644 index 0000000..874b378 --- /dev/null +++ b/Python_basics.ipynb @@ -0,0 +1,3504 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [], + "collapsed_sections": [ + "ANaO4zdgXyIR", + "kvp5aXdbvVcu", + "GpoO20JTE9pl", + "dnXbrtNzXZ_a", + "mi0RlSoBdFb-", + "MgsfE_LfkUTs", + "WaR5qxglaJ3N", + "Zgmgycox2Epn" + ], + "authorship_tag": "ABX9TyNPMdMyTYYm917vie/fsemo", + "include_colab_link": true + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "source": [ + "# Lists" + ], + "metadata": { + "id": "ANaO4zdgXyIR" + } + }, + { + "cell_type": "markdown", + "source": [ + " In Python, a list is a versatile and commonly used data structure that allows you to store and manipulate a collection of elements. Lists are mutable, meaning you can modify their contents by adding, removing, or modifying elements. Let's dive into the basics of Python lists:" + ], + "metadata": { + "id": "91-HpMqxXsxu" + } + }, + { + "cell_type": "markdown", + "source": [ + "A list is a widely used versatile data structure that allows you to store a collection of items. Lists are ordered, mutable (modifiable), and can contain elements of different data types, such as strings, integers, floats, and even other lists. Lists are defined by enclosing a comma-separated sequence of elements within square brackets []. You can access, modify, and perform various operations on the elements of a list.\n", + "\n", + "Here is the syntax for lists:\n", + "\n", + "my_list = [element1, element2, element3, ...]\n", + "\n", + "In the above syntax,\n", + "\n", + "my_list: This is the name of the list variable that you choose.\n", + "\n", + "[element1, element2, element3, ...]: These are the elements you want to store in the list, separated by commas and enclosed in square brackets." + ], + "metadata": { + "id": "XTj1e93Bt_gu" + } + }, + { + "cell_type": "code", + "source": [ + "# Create a list of integers\n", + "numbers = [1, 2, 3, 4, 5]\n", + "\n", + "# Access and print elements of the list\n", + "print(\"The first element is:\", numbers[0])\n", + "print(\"The third element is:\", numbers[2])\n", + "\n", + "# Modify an element of the list\n", + "numbers[1] = 10\n", + "\n", + "# Add an element to the end of the list\n", + "numbers.append(6)\n", + "\n", + "# Remove an element from the list\n", + "numbers.remove(3)\n", + "\n", + "# Find the length of the list\n", + "length = len(numbers)\n", + "\n", + "# Check if an element is in the list\n", + "if 4 in numbers:\n", + " print(\"4 is in the list\")\n", + "\n", + "# Iterate through the list\n", + "print(\"List elements:\")\n", + "for num in numbers:\n", + " print(num)\n", + "\n", + "# Sort the list in ascending order\n", + "numbers.sort()\n", + "\n", + "# Reverse the list\n", + "numbers.reverse()\n", + "\n", + "# Create a list of mixed data types\n", + "mixed_list = [1, \"apple\", 3.14, True]\n", + "\n", + "# Nested lists (lists within a list)\n", + "nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n", + "\n", + "# Access elements of a nested list\n", + "print(\"Element at row 2, column 3:\", nested_list[1][2])" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "tt12SwXfuM72", + "outputId": "e7464c69-f576-4d28-b79c-b2764e59f8b7" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "The first element is: 1\n", + "The third element is: 3\n", + "4 is in the list\n", + "List elements:\n", + "1\n", + "10\n", + "4\n", + "5\n", + "6\n", + "Element at row 2, column 3: 6\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "The above code begins by creating a list named numbers using the list data structure in Python, with the syntax:\n", + "\n", + "numbers = [1, 2, 3, 4, 5]\n", + "\n", + "This list contains five integer elements. Subsequently, the code showcases various list operations, including element access and modification using index positions (e.g., numbers[0] accesses the first element), appending elements to the list using the append() method, removing elements by value with the remove() method, finding the length of the list using the len() function, checking for the presence of an element using the in operator, and iterating through the list using a for loop.\n", + "\n", + "It also demonstrates list sorting and reversing using the sort() and reverse() methods. Furthermore, the code defines a nested list called nested_list, which contains three inner lists.\n", + "\n", + "Finally, it shows how to access an element within the nested list with the syntax:\n", + "\n", + "Nested_list[1][2]\n", + "\n", + "This accesses the element at row 2, column 3, which is 6." + ], + "metadata": { + "id": "6PIcJTL6ubVk" + } + }, + { + "cell_type": "markdown", + "source": [ + "###Creating Lists:\n", + "You can create a list by enclosing a sequence of elements in square brackets []. Elements in a list can be of any data type, and they can be heterogeneous (i.e., different data types within the same list)." + ], + "metadata": { + "id": "hORq-m-CX-V-" + } + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "DlRiR9N3WFK0" + }, + "outputs": [], + "source": [ + "# Creating an empty list\n", + "empty_list = []\n", + "\n", + "# Creating a list with elements\n", + "fruits = [\"apple\", \"orange\", \"banana\", \"grape\"]\n", + "\n", + "# Mixed data types in a list\n", + "mixed_list = [1, \"hello\", 3.14, True]\n" + ] + }, + { + "cell_type": "markdown", + "source": [ + "Accessing Elements:\n", + "You can access elements in a list using indexing. The index starts from 0 for the first element, 1 for the second element, and so on." + ], + "metadata": { + "id": "8z-hwIT9ZvbO" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = [\"apple\", \"orange\", \"banana\", \"grape\"]\n", + "\n", + "# Accessing elements\n", + "first_fruit = fruits[0]\n", + "second_fruit = fruits[1]\n", + "\n", + "print(first_fruit) # Output: apple\n", + "print(second_fruit) # Output: orange\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "FHweXKXmYCcJ", + "outputId": "2b69f3b7-6227-4089-a381-3a317b86cf3f" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "apple\n", + "orange\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Negative indexing is also allowed, where -1 represents the last element, -2 represents the second-to-last element, and so on." + ], + "metadata": { + "id": "_qDdJ3xSZ943" + } + }, + { + "cell_type": "code", + "source": [ + "last_fruit = fruits[-1]\n", + "second_last_fruit = fruits[-2]\n", + "\n", + "print(last_fruit) # Output: grape\n", + "print(second_last_fruit) # Output: banana\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "zFTZ65y-Yess", + "outputId": "af908406-e990-4f92-824d-5294c8fb583f" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "grape\n", + "banana\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Slicing:\n", + "You can extract a portion of a list using slicing. Slicing is done using the start:stop:step notation." + ], + "metadata": { + "id": "AkaRRcSTaGiO" + } + }, + { + "cell_type": "code", + "source": [ + "numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", + "\n", + "# Extracting a sublist\n", + "subset = numbers[2:7] # Elements at index 2, 3, 4, 5, 6\n", + "print(subset) # Output: [2, 3, 4, 5, 6]\n", + "\n", + "# Slicing with a step\n", + "even_numbers = numbers[2:9:2] # list from 2nd element to 9th element with a step of 2 elements at a time\n", + "print(even_numbers) # Output: [2, 4, 6, 8]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "9tJByrehaDxw", + "outputId": "da49b17e-a08b-4895-e197-53a04402468f" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[2, 3, 4, 5, 6]\n", + "[2, 4, 6, 8]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Modifying Lists:\n", + "Lists are mutable, meaning you can modify them by adding, removing, or updating elements." + ], + "metadata": { + "id": "NrwYG-ivaLLZ" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = [\"apple\", \"orange\", \"banana\", \"grape\"]\n", + "\n", + "# Modifying an element\n", + "fruits[1] = \"kiwi\"\n", + "print(fruits) # Output: [\"apple\", \"kiwi\", \"banana\", \"grape\"]\n", + "\n", + "# Adding elements to the end\n", + "fruits.append(\"melon\")\n", + "print(fruits) # Output: [\"apple\", \"kiwi\", \"banana\", \"grape\", \"melon\"]\n", + "\n", + "# Inserting an element at a specific index\n", + "fruits.insert(1, \"pear\")\n", + "print(fruits) # Output: [\"apple\", \"pear\", \"kiwi\", \"banana\", \"grape\", \"melon\"]\n", + "\n", + "# Removing an element by value\n", + "fruits.remove(\"banana\")\n", + "print(fruits) # Output: [\"apple\", \"pear\", \"kiwi\", \"grape\", \"melon\"]\n", + "\n", + "# Removing an element by index\n", + "removed_fruit = fruits.pop(2)\n", + "print(fruits) # Output: [\"apple\", \"pear\", \"grape\", \"melon\"]\n", + "print(removed_fruit) # Output: kiwi\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "YqO6u7wUaIyo", + "outputId": "365205af-ab8d-439b-e25f-e6fc384fc8e0" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "['apple', 'kiwi', 'banana', 'grape']\n", + "['apple', 'kiwi', 'banana', 'grape', 'melon']\n", + "['apple', 'pear', 'kiwi', 'banana', 'grape', 'melon']\n", + "['apple', 'pear', 'kiwi', 'grape', 'melon']\n", + "['apple', 'pear', 'grape', 'melon']\n", + "kiwi\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "List Methods:\n", + "Python lists come with several built-in methods for various operations. Here are a few examples:" + ], + "metadata": { + "id": "ToijU98naW8G" + } + }, + { + "cell_type": "code", + "source": [ + "numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]\n", + "\n", + "# Sorting a list\n", + "numbers.sort()\n", + "print(numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]\n", + "\n", + "# Reversing a list\n", + "numbers.reverse()\n", + "print(numbers) # Output: [9, 6, 5, 5, 4, 3, 2, 1, 1]\n", + "\n", + "# Finding the index of an element\n", + "index_of_5 = numbers.index(5)\n", + "print(index_of_5) # Output: 2\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "TbDxs_9YaMxy", + "outputId": "c0646b82-607c-4797-e4cb-b38c03da4421" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[1, 1, 2, 3, 4, 5, 5, 6, 9]\n", + "[9, 6, 5, 5, 4, 3, 2, 1, 1]\n", + "2\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Count:\n", + "\n", + "The count method returns the number of occurrences of a specified element in the list." + ], + "metadata": { + "id": "DpNfgcFjbWV0" + } + }, + { + "cell_type": "code", + "source": [ + "numbers = [1, 2, 3, 4, 2, 5, 2]\n", + "count_of_2 = numbers.count(2)\n", + "print(count_of_2) # Output: 3\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "uU3TdY4YaYvT", + "outputId": "10f74f3b-c60e-4ed4-c25b-85cb9d6fd271" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "3\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Extend:\n", + "\n", + "The extend method adds the elements of another iterable (e.g., list, tuple) to the end of the list." + ], + "metadata": { + "id": "1Ajy7EPSbbD4" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = [\"apple\", \"banana\"]\n", + "more_fruits = [\"orange\", \"kiwi\"]\n", + "fruits.extend(more_fruits)\n", + "print(fruits) # Output: [\"apple\", \"banana\", \"orange\", \"kiwi\"]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Nbq3pheCbYDc", + "outputId": "f66b992f-bf06-4584-bfdd-c7729fc9bfad" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "['apple', 'banana', 'orange', 'kiwi']\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Clear:\n", + "\n", + "The clear method removes all elements from the list, leaving it empty." + ], + "metadata": { + "id": "ipDytdW3bhRK" + } + }, + { + "cell_type": "code", + "source": [ + "numbers = [1, 2, 3, 4, 5]\n", + "numbers.clear()\n", + "print(numbers) # Output: []\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "yb1ez992be7w", + "outputId": "f30a5579-3659-41ac-e197-e19ca13963ac" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Copy:\n", + "\n", + "The copy method creates a shallow copy of the list." + ], + "metadata": { + "id": "XY2RXle5blNo" + } + }, + { + "cell_type": "code", + "source": [ + "original_list = [1, 2, 3]\n", + "copied_list = original_list.copy()\n" + ], + "metadata": { + "id": "deoQ1qd8bjD6" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Reverse:\n", + "\n", + "The reverse method reverses the elements of the list in-place." + ], + "metadata": { + "id": "vDX1_bV7br4H" + } + }, + { + "cell_type": "code", + "source": [ + "numbers = [1, 2, 3, 4, 5]\n", + "numbers.reverse()\n", + "print(numbers) # Output: [5, 4, 3, 2, 1]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "vKrkZ8lMbmpp", + "outputId": "a7ccb4dd-7ed4-4e13-ff19-b90e877341a1" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[5, 4, 3, 2, 1]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Index with Start and End:\n", + "\n", + "The index method can take optional start and end parameters to search for an element within a specific range." + ], + "metadata": { + "id": "otwc23sbbvrT" + } + }, + { + "cell_type": "code", + "source": [ + "numbers = [1, 2, 3, 4, 2, 5, 2]\n", + "index_of_2_after_2nd_position = numbers.index(2, 2)\n", + "print(index_of_2_after_2nd_position) # Output: 4\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "0lBAA5GSbtaY", + "outputId": "593c15c3-0003-46ec-8987-10a76d3f5f23" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "4\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Pop with Index:\n", + "\n", + "The pop method can take an index as an argument to remove and return the element at that index." + ], + "metadata": { + "id": "FKMUqwK1bzLB" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = [\"apple\", \"banana\", \"orange\"]\n", + "popped_fruit = fruits.pop(1)\n", + "print(popped_fruit) # Output: banana\n", + "print(fruits) # Output: [\"apple\", \"orange\"]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "lOK_eEcWbxJ0", + "outputId": "e9fed81f-2716-4a9e-c13d-72f40f355191" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "banana\n", + "['apple', 'orange']\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Remove with Value:\n", + "\n", + "The remove method removes the first occurrence of a specified value from the list." + ], + "metadata": { + "id": "JkBzoPjCb2t1" + } + }, + { + "cell_type": "code", + "source": [ + "numbers = [1, 2, 3, 4, 2, 5, 2]\n", + "numbers.remove(2)\n", + "print(numbers) # Output: [1, 3, 4, 5, 2]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "kkVPzGxzb02F", + "outputId": "d3e7ff66-b990-4fe0-f6a8-5a3b8872945b" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[1, 3, 4, 2, 5, 2]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "============================================================================================================" + ], + "metadata": { + "id": "9dKcAAcuvMaS" + } + }, + { + "cell_type": "markdown", + "source": [ + "# Arrays" + ], + "metadata": { + "id": "kvp5aXdbvVcu" + } + }, + { + "cell_type": "markdown", + "source": [ + "Arrays in Python (using array module):\n", + "The array module provides a more memory-efficient way to store arrays of numeric values.\n", + "\n", + "Note: While array provides more memory efficiency for large datasets of homogeneous numeric types, lists are generally more versatile and widely used in Python.\n", + "\n", + "NumPy Arrays:\n", + "For more advanced array manipulation and numerical operations, the NumPy library is often used. NumPy provides a powerful array object that supports multidimensional arrays and a wide range of mathematical operations." + ], + "metadata": { + "id": "lP2ELjDCvcDW" + } + }, + { + "cell_type": "markdown", + "source": [ + "Advantages of array Module:\n", + "\n", + "\n", + "Memory Efficiency: The array module can be more memory-efficient than lists for large datasets of homogeneous numeric types.\n", + "\n", + "\n", + "Typecode Enforcement: The typecode enforces that all elements in the array have the specified data type.\n", + "\n", + "\n", + "\n", + "Limitations:\n", + "\n", + "\n", + "Lack of Flexibility: Unlike lists, arrays created using the array module are less flexible because they can only store elements of the specified data type.\n", + "\n", + "Homogeneity Requirement: Unlike lists, array requires all elements to be of the same data type.\n", + "\n", + "Limited Functionality: array objects provide basic functionality for array operations, but they lack many of the advanced operations and functions provided by libraries like NumPy." + ], + "metadata": { + "id": "E8GNg5gfvz8V" + } + }, + { + "cell_type": "code", + "source": [ + "from array import array\n", + "\n", + "# Creating an array of integers\n", + "integer_array = array('i', [1, 2, 3, 4, 5])\n", + "\n", + "# Accessing elements by index\n", + "first_element = integer_array[0] # 1\n" + ], + "metadata": { + "id": "BgD769hZb326" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "source": [ + "from array import array\n", + "\n", + "# Creating an array of floating-point numbers\n", + "float_array = array('f', [1.0, 2.5, 3.7, 4.2])\n", + "\n", + "# Accessing elements\n", + "print(float_array[1]) # Output: 2.5\n", + "\n", + "# Modifying an element\n", + "float_array[2] = 5.0\n", + "print(float_array) # Output: array('f', [1.0, 2.5, 5.0, 4.2])\n" + ], + "metadata": { + "id": "pt4b5csaaAJG" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "## Example 1: Integer Array ('i' Typecode)" + ], + "metadata": { + "id": "YqXy-lGoELQI" + } + }, + { + "cell_type": "code", + "source": [ + "from array import array\n", + "\n", + "# Creating an array of signed integers\n", + "integer_array = array('i', [1, 2, 3, 4, 5])\n", + "\n", + "# Accessing elements\n", + "print(integer_array[2]) # Output: 3\n", + "\n", + "# Modifying an element\n", + "integer_array[0] = 10\n", + "print(integer_array) # Output: array('i', [10, 2, 3, 4, 5])\n" + ], + "metadata": { + "id": "6kTTKKL-ESNV" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "## Example 2: Floating-Point Array ('f' Typecode)" + ], + "metadata": { + "id": "CupCk7t9EX4r" + } + }, + { + "cell_type": "code", + "source": [ + "from array import array\n", + "\n", + "# Creating an array of floating-point numbers\n", + "float_array = array('f', [1.0, 2.5, 3.7, 4.2])\n", + "\n", + "# Accessing elements\n", + "print(float_array[1]) # Output: 2.5\n", + "\n", + "# Modifying an element\n", + "float_array[2] = 5.0\n", + "print(float_array) # Output: array('f', [1.0, 2.5, 5.0, 4.2])\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "wmQudP3aEeNi", + "outputId": "8ef9b84a-7b0c-4b89-9f6e-eba1a2ee3c6c" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "2.5\n", + "array('f', [1.0, 2.5, 5.0, 4.199999809265137])\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Example 3: Double-Precision Floating-Point Array ('d' Typecode)" + ], + "metadata": { + "id": "YBwIoY4PEh5M" + } + }, + { + "cell_type": "code", + "source": [ + "from array import array\n", + "\n", + "# Creating an array of double-precision floating-point numbers\n", + "double_array = array('d', [1.0, 2.5, 3.7, 4.2])\n", + "\n", + "# Accessing elements\n", + "print(double_array[3]) # Output: 4.2\n", + "\n", + "# Modifying an element\n", + "double_array[1] = 6.0\n", + "print(double_array) # Output: array('d', [1.0, 6.0, 3.7, 4.2])\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "gK9t90-oElRi", + "outputId": "88df023a-3437-4a70-8f54-32cccb60d715" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "4.2\n", + "array('d', [1.0, 6.0, 3.7, 4.2])\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Example 4: Byte Array ('b' Typecode)" + ], + "metadata": { + "id": "kReNPHobEpd7" + } + }, + { + "cell_type": "code", + "source": [ + "from array import array\n", + "\n", + "# Creating an array of bytes\n", + "byte_array = array('b', [65, 66, 67, 68])\n", + "\n", + "# Accessing elements\n", + "print(byte_array[2]) # Output: 67\n", + "\n", + "# Modifying an element\n", + "byte_array[1] = 70\n", + "print(byte_array) # Output: array('b', [65, 70, 67, 68])\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "v4PULb32Er7-", + "outputId": "52af4ab1-35db-4141-c2ec-f586485bb3da" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "67\n", + "array('b', [65, 70, 67, 68])\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "===================================================================================================================" + ], + "metadata": { + "id": "JZxO7nJFaA8M" + } + }, + { + "cell_type": "markdown", + "source": [ + "# Dictionary" + ], + "metadata": { + "id": "GpoO20JTE9pl" + } + }, + { + "cell_type": "markdown", + "source": [ + "Dictionaries are unordered collections of key-value pairs. Each key in a dictionary is unique, and it is associated with a corresponding value. A dictionary is defined by enclosing a comma-separated sequence of key-value pairs within curly braces {}. They are used for efficient data retrieval and storage of key-associated values.\n", + "\n", + "Here is the syntax for creating dictionaries:\n", + "\n", + "my_dict = {key1: value1, key2: value2, key3: value3, ...}\n", + "In the above syntax,\n", + "\n", + "my_dict: This is the name of the dictionary variable.\n", + "\n", + "{key1: value1, key2: value2, key3: value3, ...}: These are the key-value pairs enclosed in curly braces and separated by commas.\n", + "\n", + "Here is an example of using a dictionary in Python:" + ], + "metadata": { + "id": "R7BgQe89viAW" + } + }, + { + "cell_type": "code", + "source": [ + "# Create a dictionary of key-value pairs\n", + "my_dict = {\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\n", + "\n", + "# Access values using keys\n", + "name = my_dict[\"name\"]\n", + "age = my_dict[\"age\"]\n", + "\n", + "# Attempting to access a non-existent key will raise a KeyError\n", + "# Uncommenting the line below will cause an error\n", + "# country = my_dict[\"country\"]\n", + "\n", + "# Check if a key is in the dictionary\n", + "if \"city\" in my_dict:\n", + " print(\"City is in the dictionary\")\n", + "\n", + "# Find the number of key-value pairs in the dictionary\n", + "num_items = len(my_dict)\n", + "\n", + "# Iterate through keys and values\n", + "print(\"Dictionary elements:\")\n", + "for key, value in my_dict.items():\n", + " print(key, \":\", value)\n", + "\n", + "# Modify a value associated with a key\n", + "my_dict[\"age\"] = 31\n", + "\n", + "# Add a new key-value pair to the dictionary\n", + "my_dict[\"country\"] = \"USA\"\n", + "\n", + "# Remove a key-value pair from the dictionary\n", + "del my_dict[\"city\"]" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "wqEwzDeOvlwB", + "outputId": "25df53ad-ac4c-48e0-8498-b942c5639bc8" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "City is in the dictionary\n", + "Dictionary elements:\n", + "name : John\n", + "age : 30\n", + "city : New York\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "\n", + "In Python, a dictionary is a mutable, unordered collection of key-value pairs, where each key must be unique. Dictionaries are sometimes referred to as \"associative arrays\" or \"hash maps\" in other programming languages. They provide an efficient way to store and retrieve data by associating values with unique keys.\n", + "\n", + "\n", + "Dictionaries are a fundamental data structure in Python and are widely used for various tasks, such as representing JSON-like structures, configuration settings, or any scenario where data needs to be associated with unique keys. They are flexible, efficient, and offer fast key-based access to values.\n", + "\n", + "\n", + "### Creating a Dictionary:\n", + "You can create a dictionary using curly braces {} and specifying key-value pairs." + ], + "metadata": { + "id": "G4z5SNBwFFAG" + } + }, + { + "cell_type": "code", + "source": [ + "# Creating an empty dictionary\n", + "empty_dict = {}\n", + "\n", + "# Creating a dictionary with key-value pairs\n", + "student = {\n", + " \"name\": \"John Doe\",\n", + " \"age\": 20,\n", + " \"grade\": \"A\",\n", + " \"is_enrolled\": True\n", + "}\n" + ], + "metadata": { + "id": "DxSAqGQnFOF5" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Accessing Elements:\n", + "You can access the values in a dictionary using the keys." + ], + "metadata": { + "id": "U6MGqV0tFRb5" + } + }, + { + "cell_type": "code", + "source": [ + "# Accessing values by keys\n", + "print(student[\"name\"]) # Output: John Doe\n", + "print(student[\"age\"]) # Output: 20\n", + "print(student[\"is_enrolled\"]) # Output: True\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "3k72cVygFfLd", + "outputId": "643836b4-51fc-4717-df4c-9f042621f4fc" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "John Doe\n", + "20\n", + "True\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Modifying and Adding Elements:\n", + "You can modify the value associated with a key or add new key-value pairs." + ], + "metadata": { + "id": "JXBC4FaBFiSy" + } + }, + { + "cell_type": "code", + "source": [ + "# Modifying a value\n", + "student[\"age\"] = 21\n", + "\n", + "# Adding a new key-value pair\n", + "student[\"major\"] = \"Computer Science\"\n", + "\n" + ], + "metadata": { + "id": "o1dKyz62Fj9d" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Functions in dictionary" + ], + "metadata": { + "id": "gtlyPRj-PeO7" + } + }, + { + "cell_type": "markdown", + "source": [ + "**get() Method:**\n", + "\n", + "The get() method returns the value for a specified key. If the key is not found, it returns a default value (which defaults to None)." + ], + "metadata": { + "id": "54isLVHLPq0a" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "age = student.get(\"age\", 0) # Returns 20\n", + "grade = student.get(\"grade\", \"N/A\") # Returns \"N/A\"\n" + ], + "metadata": { + "id": "3mLCe9MyPy6o" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**setdefault() Method:**\n", + "\n", + "The setdefault() method is used to set the default value of a key if it doesn't exist in the dictionary." + ], + "metadata": { + "id": "z8Mpk8lhP3TH" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "student.setdefault(\"grade\", \"A\") # If \"grade\" key exists, returns \"A\"; otherwise, sets \"grade\" to \"A\" and returns \"A\"\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "hm1lmbqzP6Po", + "outputId": "8fb5cd1e-fb52-4697-f6c8-f79596405f37" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'A'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 12 + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**update() Method:**\n", + "\n", + "The update() method updates the dictionary with elements from another dictionary or from an iterable of key-value pairs." + ], + "metadata": { + "id": "Tv0cLGlfP-st" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "additional_info = {\"grade\": \"A\", \"major\": \"Computer Science\"}\n", + "student.update(additional_info)\n", + "# student is now {\"name\": \"John Doe\", \"age\": 20, \"grade\": \"A\", \"major\": \"Computer Science\"}\n" + ], + "metadata": { + "id": "V1DKKYj4QC6W" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**items() Method:**\n", + "\n", + "The items() method returns a view of dictionary key-value pairs as tuples." + ], + "metadata": { + "id": "rASfmtVaQKii" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20, \"grade\": \"A\"}\n", + "for key, value in student.items():\n", + " print(key, value)\n", + "# Output:\n", + "# name John Doe\n", + "# age 20\n", + "# grade A\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "OWuR4eINQTH0", + "outputId": "73a46867-f317-466f-d4a3-f1977633e2c9" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "name John Doe\n", + "age 20\n", + "grade A\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**popitem() Method:**\n", + "\n", + "The popitem() method removes and returns the last inserted key-value pair as a tuple." + ], + "metadata": { + "id": "6X4mjYqOQTna" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20, \"grade\": \"A\"}\n", + "removed_item = student.popitem() # Removes and returns ('grade', 'A')\n" + ], + "metadata": { + "id": "X1YdboLKQULI" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**Merging Dictionaries:**\n", + "\n", + "You can use the {**dict1, **dict2} syntax to merge dictionaries in Python 3.5 and above." + ], + "metadata": { + "id": "qoou2I7XQUnd" + } + }, + { + "cell_type": "code", + "source": [ + "dict1 = {\"a\": 1, \"b\": 2}\n", + "dict2 = {\"b\": 3, \"c\": 4}\n", + "merged_dict = {**dict1, **dict2} # {'a': 1, 'b': 3, 'c': 4}\n" + ], + "metadata": { + "id": "NcXCdVnaQzFg" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Dictionary Methods:\n", + "Dictionaries in Python come with a variety of methods for common operations." + ], + "metadata": { + "id": "iINHcJrfFoZS" + } + }, + { + "cell_type": "code", + "source": [ + "# Getting all keys\n", + "keys = student.keys() # Output: dict_keys(['name', 'age', 'grade', 'is_enrolled', 'major'])\n", + "\n", + "# Getting all values\n", + "values = student.values()\n", + "\n", + "# Checking if a key exists\n", + "is_name_present = \"name\" in student # Output: True\n", + "\n", + "# Removing a key-value pair\n", + "removed_grade = student.pop(\"grade\") # Output: \"A\"\n" + ], + "metadata": { + "id": "MmwvjNVyFpm-" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Iterating Through a Dictionary:\n", + "You can iterate through the keys or key-value pairs of a dictionary." + ], + "metadata": { + "id": "o6IMeBS5FxAz" + } + }, + { + "cell_type": "code", + "source": [ + "# Iterating through keys\n", + "for key in student:\n", + " print(key, student[key])\n", + "\n", + "# Iterating through key-value pairs\n", + "for key, value in student.items():\n", + " print(key, value)\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "TRA00ZmaF0_Z", + "outputId": "bb5d05bd-7c33-4077-d954-28a8fb522ffe" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "name John Doe\n", + "age 21\n", + "is_enrolled True\n", + "major Computer Science\n", + "name John Doe\n", + "age 21\n", + "is_enrolled True\n", + "major Computer Science\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Dictionary Comprehension:\n", + "Similar to list comprehensions, you can use dictionary comprehensions to create dictionaries in a concise manner." + ], + "metadata": { + "id": "9wbBsaAGF4Vu" + } + }, + { + "cell_type": "code", + "source": [ + "squared_numbers = {x: x**2 for x in range(1, 6)}\n", + "# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}\n" + ], + "metadata": { + "id": "an_LZa2gF5qf" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Nested Dictionaries:\n", + "Dictionaries can also contain other dictionaries, forming nested structures." + ], + "metadata": { + "id": "aFP2R1SKF7sK" + } + }, + { + "cell_type": "code", + "source": [ + "students = {\n", + " \"john\": {\"age\": 20, \"grade\": \"A\"},\n", + " \"alice\": {\"age\": 22, \"grade\": \"B\"}\n", + "}\n" + ], + "metadata": { + "id": "L4a-syq5F_pq" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "## Methods in dictionary" + ], + "metadata": { + "id": "ccJSAyckREk5" + } + }, + { + "cell_type": "markdown", + "source": [ + "### Methods for Accessing Elements:\n", + "\n", + "\n", + "\n", + "***get(key, default): ***\n", + "\n", + "Returns the value for the specified key. If the key is not found, it returns the default value (or None if not specified)." + ], + "metadata": { + "id": "VhLYNHQKRI7L" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "age = student.get(\"age\", 0) # Returns 20\n", + "grade = student.get(\"grade\", \"N/A\") # Returns \"N/A\"\n" + ], + "metadata": { + "id": "YhQMI2P2RdE8" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**keys():**\n", + "\n", + "Returns a view of dictionary keys." + ], + "metadata": { + "id": "MMVjNLvkRe6z" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "key_view = student.keys() # Returns dict_keys(['name', 'age'])\n" + ], + "metadata": { + "id": "daUipNOuRjeY" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**values():**\n", + "\n", + " Returns a view of dictionary values." + ], + "metadata": { + "id": "cmBzJZzERmot" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "value_view = student.values()\n" + ], + "metadata": { + "id": "qtZLW5HKRp_3" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**items(): **\n", + "\n", + "Returns a view of dictionary key-value pairs as tuples." + ], + "metadata": { + "id": "FScHUgq_R7KI" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "items_view = student.items()\n" + ], + "metadata": { + "id": "ZDqeK8gwR9-y" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Methods for Modifying Dictionaries:\n", + "\n", + "**update(dictionary):**\n", + "\n", + "Updates the dictionary with elements from another dictionary or from an iterable of key-value pairs." + ], + "metadata": { + "id": "JWcIKvrnSByZ" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "additional_info = {\"grade\": \"A\", \"major\": \"Computer Science\"}\n", + "student.update(additional_info)\n" + ], + "metadata": { + "id": "1ziYJHILSH4x" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**setdefault(key, default):**\n", + "\n", + "Returns the value for the specified key. If the key is not found, it inserts the key with the specified default value." + ], + "metadata": { + "id": "3DfEUyRvSKIA" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "student.setdefault(\"grade\", \"A\") # If \"grade\" key exists, returns \"A\"; otherwise, sets \"grade\" to \"A\" and returns \"A\"\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "VnF2jrBtSOz_", + "outputId": "f35ab2be-6909-4bd0-9a68-c7d6dc2bfbf3" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'A'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 21 + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Methods for Removing Elements:\n", + "\n", + "**pop(key, default):**\n", + "\n", + "Removes the item with the specified key and returns its value. If the key is not found, it returns the default value (or raises a KeyError if not specified)." + ], + "metadata": { + "id": "dUMi5dN2SWf-" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "removed_age = student.pop(\"age\") # Removes and returns 20\n" + ], + "metadata": { + "id": "-i3GVjplSgn5" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**popitem():**\n", + "\n", + "Removes and returns the last inserted key-value pair as a tuple." + ], + "metadata": { + "id": "1p7oAzcsSibU" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "removed_item = student.popitem() # Removes and returns ('age', 20)\n" + ], + "metadata": { + "id": "hgp4xe8bTUfQ" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Other Methods:\n", + "**clear():**\n", + "\n", + "Removes all items from the dictionary." + ], + "metadata": { + "id": "d3zF19yITbDK" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "student.clear() # Clears all items, making the dictionary empty\n" + ], + "metadata": { + "id": "JdO-mbeQTjOn" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**copy():**\n", + "\n", + "Returns a shallow copy of the dictionary." + ], + "metadata": { + "id": "_yO1g1DaWLjI" + } + }, + { + "cell_type": "code", + "source": [ + "student = {\"name\": \"John Doe\", \"age\": 20}\n", + "student_copy = student.copy()\n" + ], + "metadata": { + "id": "hSmDNn8eWOk4" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**deepcopy():**\n", + "\n", + "to do deep copy in python\n", + "\n" + ], + "metadata": { + "id": "rGMjBcwHW4ui" + } + }, + { + "cell_type": "code", + "source": [ + "from copy import deepcopy\n", + "test1 = {\"name\": \"akshat\", \"name1\": \"manjeet\", \"name2\": \"vashu\"}\n", + "\n", + "# method to copy dictionary using deepcopy\n", + "test2 = deepcopy(test1)" + ], + "metadata": { + "id": "vkTFMyWvXIkk" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "# Sets" + ], + "metadata": { + "id": "dnXbrtNzXZ_a" + } + }, + { + "cell_type": "markdown", + "source": [ + "A set is an unordered collection of unique elements. Sets are defined by enclosing a comma-separated sequence of elements within curly braces {} or by using the set() constructor. Sets are primarily used for tasks that involve storing and manipulating a collection of distinct values.\n", + "\n", + "Here is the syntax for creating sets:\n", + "\n", + "my_set = {element1, element2, element3, ...}\n", + " OR\n", + "my_set = set([element1, element2, element3, ...])\n", + "In the above syntax,\n", + "\n", + "my_set: This is the name of the set variable.\n", + "\n", + "{element1, element2, element3, ...}: These are the elements.\n", + "\n", + "Here is an example of working with sets in Python:" + ], + "metadata": { + "id": "i4CVjn9ivNQg" + } + }, + { + "cell_type": "code", + "source": [ + "# Create a set of unique integers\n", + "my_set = {1, 2, 3, 4, 5}\n", + "\n", + "# Attempting to add a duplicate element will have no effect\n", + "my_set.add(2)\n", + "\n", + "# Remove an element from the set\n", + "my_set.remove(3)\n", + "\n", + "# Check if an element is in the set\n", + "if 4 in my_set:\n", + " print(\"4 is in the set\")\n", + "\n", + "# Find the length of the set\n", + "length = len(my_set)\n", + "\n", + "# Iterate through the set\n", + "print(\"Set elements:\")\n", + "for item in my_set:\n", + " print(item)\n", + "\n", + "# Perform set operations (union, intersection, difference)\n", + "set1 = {1, 2, 3}\n", + "set2 = {3, 4, 5}\n", + "union_set = set1 | set2\n", + "intersection_set = set1 & set2\n", + "difference_set = set1 - set2\n", + "\n", + "# Convert a list to a set to remove duplicates\n", + "my_list = [1, 2, 2, 3, 4, 4, 5]\n", + "unique_set = set(my_list)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "NsgO6XrYvT04", + "outputId": "b225740f-1e92-4443-aeef-dbd0f78c22ec" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "4 is in the set\n", + "Set elements:\n", + "1\n", + "2\n", + "4\n", + "5\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "In Python, a set is an unordered collection of unique elements. Sets are useful when you want to store multiple items in a single variable, but you are only interested in the unique items, and their order doesn't matter. Sets are implemented using hash tables, which makes membership tests (checking if an element is in the set) very efficient.\n", + "\n", + "\n", + "Sets provide a powerful and efficient way to work with unique collections of data in Python. They are particularly useful in scenarios where uniqueness is a key requirement, and the order of elements is not important.\n", + "\n", + "\n", + "Here are some key characteristics and operations related to sets in Python:\n", + "\n", + "\n", + "\n", + "**Creating a Set:**\n", + "You can create a set using curly braces {} or by using the set() constructor." + ], + "metadata": { + "id": "OCGN6gK-XfUB" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = {\"apple\", \"banana\", \"orange\"}\n", + "empty_set = set()\n" + ], + "metadata": { + "id": "NvJmgjj0XodE" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Adding and Removing Elements:\n", + "1. **add(element):**\n", + "\n", + "Adds an element to the set. If the element is already present, the set remains unchanged." + ], + "metadata": { + "id": "omYMvZJJXqD7" + } + }, + { + "cell_type": "code", + "source": [ + "fruits.add(\"grape\")\n" + ], + "metadata": { + "id": "1PC8kNKnXxHk" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "2. **remove(element):**\n", + "\n", + "Removes the specified element from the set. Raises a KeyError if the element is not found." + ], + "metadata": { + "id": "pWmD0ZuVXypn" + } + }, + { + "cell_type": "code", + "source": [ + "fruits.remove(\"banana\")\n" + ], + "metadata": { + "id": "V-NTbX8gX4qe" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "3. **discard(element):**\n", + "\n", + "Removes the specified element from the set if it is present. If the element is not present, the set remains unchanged." + ], + "metadata": { + "id": "c9HV8PdfX7mw" + } + }, + { + "cell_type": "code", + "source": [ + "fruits.discard(\"banana\")\n" + ], + "metadata": { + "id": "ooYpfX0CX-FS" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "4. **update(iterable):**\n", + "\n", + "Adds multiple elements to the set." + ], + "metadata": { + "id": "9jdOOv8RaHEt" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = {\"apple\", \"banana\"}\n", + "fruits.update([\"orange\", \"grape\"])\n" + ], + "metadata": { + "id": "y3k6tc5raOYM" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "5. **pop():**\n", + "\n", + "Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty." + ], + "metadata": { + "id": "EP-5YpNyaRQP" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = {\"apple\", \"banana\", \"orange\"}\n", + "removed_element = fruits.pop()\n" + ], + "metadata": { + "id": "9m71Rzk3aX1i" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Set Operations:\n", + "1. **Union (|):**\n", + "\n", + "Returns a new set containing all unique elements from both sets." + ], + "metadata": { + "id": "d15WobmRYCz8" + } + }, + { + "cell_type": "code", + "source": [ + "set1 = {1, 2, 3}\n", + "set2 = {3, 4, 5}\n", + "union_set = set1 | set2 # Output: {1, 2, 3, 4, 5}\n" + ], + "metadata": { + "id": "GsdE1VfnYSSa" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "2. **Intersection (&):** Returns a new set containing only elements that are common to both sets." + ], + "metadata": { + "id": "OqHtEVM_YUcq" + } + }, + { + "cell_type": "code", + "source": [ + "intersection_set = set1 & set2 # Output: {3}\n" + ], + "metadata": { + "id": "hxv0-wybYaQa" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "3. **Difference (-):** Returns a new set containing elements that are in the first set but not in the second set." + ], + "metadata": { + "id": "qf_uvGV_YczI" + } + }, + { + "cell_type": "code", + "source": [ + "difference_set = set1 - set2 # Output: {1, 2}\n" + ], + "metadata": { + "id": "YnMLEeOsYi5m" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "4. **Symmetric Difference (^):**\n", + "Returns a new set containing elements that are unique to each set." + ], + "metadata": { + "id": "6lJzZjrnYkew" + } + }, + { + "cell_type": "code", + "source": [ + "symmetric_difference_set = set1 ^ set2 # Output: {1, 2, 4, 5}\n" + ], + "metadata": { + "id": "a4D4wMIGYpp4" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Other Operations:\n", + "1. **len(set):**\n", + " Returns the number of elements in the set." + ], + "metadata": { + "id": "-IOKGgxHYrkK" + } + }, + { + "cell_type": "code", + "source": [ + "num_elements = len(fruits)\n" + ], + "metadata": { + "id": "ao9KsywgYznN" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "2.**in** Membership Test:\n", + "Checks if an element is present in the set." + ], + "metadata": { + "id": "nbkWpLjTY2rx" + } + }, + { + "cell_type": "code", + "source": [ + "is_apple_present = \"apple\" in fruits # Output: True\n" + ], + "metadata": { + "id": "MaafxU0WZAnr" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "3. **clear():**\n", + "Removes all elements from the set." + ], + "metadata": { + "id": "ugkZl30QZDM2" + } + }, + { + "cell_type": "code", + "source": [ + "fruits.clear()\n" + ], + "metadata": { + "id": "jlzqRxLgZJED" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Sets and Iteration:\n", + "\n", + "Sets can be iterated using loops." + ], + "metadata": { + "id": "PJzRpqtCZQVR" + } + }, + { + "cell_type": "code", + "source": [ + "fruits = {\"apple\", \"banana\", \"orange\"}\n", + "for fruit in fruits:\n", + " print(fruit)\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Q_7zfqW8ZWI3", + "outputId": "e92e2dba-79ec-4ba0-843f-10451efcf385" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "apple\n", + "orange\n", + "banana\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**Sets and Immutability:**\n", + "\n", + "\n", + "Sets are mutable, which means you can add and remove elements after the set is created. However, the elements themselves must be immutable (e.g., numbers, strings, tuples)." + ], + "metadata": { + "id": "eAKjrEeiZbYG" + } + }, + { + "cell_type": "code", + "source": [ + "set_with_immutable_elements = {1, \"apple\", (2, 3)}\n" + ], + "metadata": { + "id": "wWsxdWiRZhQy" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "# Frozen set" + ], + "metadata": { + "id": "mi0RlSoBdFb-" + } + }, + { + "cell_type": "markdown", + "source": [ + "\n", + "In Python, a frozenset is an immutable version of a set. It shares many characteristics with sets, but once a frozenset is created, you cannot add or remove elements from it. This immutability makes frozenset suitable for scenarios where you want a collection of unique elements that should remain constant throughout the program.\n", + "\n", + "**Creating a frozenset:**\n", + "\n", + "You can create a frozenset using the frozenset() constructor by passing an iterable (e.g., a list or another set) as an argument." + ], + "metadata": { + "id": "Hx2qe4eVdI7o" + } + }, + { + "cell_type": "code", + "source": [ + "frozen_set = frozenset([1, 2, 3, 4])\n" + ], + "metadata": { + "id": "1chEFhV-faDT" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Properties and functions:\n", + "1. **Immutability:**\n", + "\n", + "Once a frozenset is created, you cannot add or remove elements from it. Attempting to use methods that modify the set will result in an AttributeError." + ], + "metadata": { + "id": "XgYcRMyyfdRn" + } + }, + { + "cell_type": "code", + "source": [ + "frozen_set.add(5) # Raises AttributeError: 'frozenset' object has no attribute 'add'\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 175 + }, + "id": "HulLVsEnfmTU", + "outputId": "3a8bde7e-a3c5-44c8-b7b5-20416d53074e" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "error", + "ename": "AttributeError", + "evalue": "'frozenset' object has no attribute 'add'", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfrozen_set\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# Raises AttributeError: 'frozenset' object has no attribute 'add'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m: 'frozenset' object has no attribute 'add'" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "2. **Hashability:**\n", + "\n", + "frozenset is hashable, which means it can be used as a key in a dictionary or an element in another set. This is because the immutability guarantees that the hash value of the frozenset remains constant." + ], + "metadata": { + "id": "AAH0jQfgVBMr" + } + }, + { + "cell_type": "code", + "source": [ + "set_of_frozensets = {frozenset([1, 2, 3]), frozenset([4, 5, 6])}\n" + ], + "metadata": { + "id": "1kEERfnuVA4k" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "3. **Membership Test:**\n", + "\n", + "You can use the in operator to check if an element is a member of the frozenset." + ], + "metadata": { + "id": "7RZocqiPVAgc" + } + }, + { + "cell_type": "code", + "source": [ + "is_present = 2 in frozen_set # Returns True\n" + ], + "metadata": { + "id": "t3qxMp1QVANs" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "4. **Iteration:**\n", + "\n", + "You can iterate over the elements of a frozenset." + ], + "metadata": { + "id": "owefP7jMU_33" + } + }, + { + "cell_type": "code", + "source": [ + "for element in frozen_set:\n", + " print(element)\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "egSjxBMbjQV-", + "outputId": "cf98f598-f1cd-4f67-de31-b22f4fa230f9" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Uses\n", + "\n", + "1. **As Dictionary Keys:**\n", + "\n", + "Since frozenset is hashable, it can be used as a key in a dictionary." + ], + "metadata": { + "id": "a51TkkvmjYiG" + } + }, + { + "cell_type": "code", + "source": [ + "dictionary_of_frozensets = {frozenset([1, 2, 3]): \"abc\", frozenset([4, 5, 6]): \"xyz\"}\n" + ], + "metadata": { + "id": "ZAg_Ko4Fjf8P" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "2. **As Elements of Other Sets:**\n", + "\n", + "frozenset can be used as elements in another set." + ], + "metadata": { + "id": "illu3TgDjimM" + } + }, + { + "cell_type": "code", + "source": [ + "set_of_frozensets = {frozenset([1, 2, 3]), frozenset([4, 5, 6])}\n" + ], + "metadata": { + "id": "g1eHHgJOjnt7" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### When to Use frozenset:\n", + "\n", + "Use a frozenset when you need a collection of unique elements that should remain constant and immutable. If you need a mutable set that you can modify during the program's execution, then use a regular set." + ], + "metadata": { + "id": "tb_RME0Hj0bu" + } + }, + { + "cell_type": "code", + "source": [ + "# Regular set (mutable)\n", + "mutable_set = {1, 2, 3}\n", + "\n", + "# Frozenset (immutable)\n", + "immutable_set = frozenset([1, 2, 3])\n" + ], + "metadata": { + "id": "LtuEeM53j8jE" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "# Tuple" + ], + "metadata": { + "id": "MgsfE_LfkUTs" + } + }, + { + "cell_type": "markdown", + "source": [ + "A tuple is an ordered and immutable (unchangeable) collection of elements. Tuples are defined by enclosing a comma-separated sequence of elements within parentheses (). Like lists, tuples can store elements of different data types. However, once a tuple is created, you cannot modify its contents. Tuples are often used when you want to ensure the data remains constant or unchangeable.\n", + "\n", + "Here is the syntax for tuples:\n", + "\n", + "my_tuple = (element1, element2, element3, ...)\n", + "In the above syntax,\n", + "\n", + "my_tuple: This is the name of the tuple variable.\n", + "\n", + "(element1, element2, element3, ...): These are the elements enclosed in parentheses and separated by commas.\n", + "\n", + "Here is an example Python program that will demonstrate the creation of tuples and some common operations on tuples:" + ], + "metadata": { + "id": "KwSKB0nouyPQ" + } + }, + { + "cell_type": "code", + "source": [ + "# Create a tuple of mixed data types\n", + "my_tuple = (1, \"apple\", 3.14, True)\n", + "\n", + "# Access elements of the tuple using indexing\n", + "print(\"The first element is:\", my_tuple[0])\n", + "print(\"The second element is:\", my_tuple[1])\n", + "\n", + "# Attempting to modify a tuple will result in an error\n", + "# Uncommenting the line below will cause an error\n", + "# my_tuple[0] = 10\n", + "\n", + "# Find the length of the tuple\n", + "length = len(my_tuple)\n", + "\n", + "# Check if an element is in the tuple\n", + "if 3.14 in my_tuple:\n", + " print(\"3.14 is in the tuple\")\n", + "\n", + "# Iterate through the tuple\n", + "print(\"Tuple elements:\")\n", + "for item in my_tuple:\n", + " print(item)\n", + "\n", + "# Concatenate tuples\n", + "tuple1 = (1, 2, 3)\n", + "tuple2 = (\"a\", \"b\", \"c\")\n", + "concatenated_tuple = tuple1 + tuple2\n", + "\n", + "# Repeat a tuple\n", + "repeated_tuple = tuple1 * 3\n", + "\n", + "# Nested tuples\n", + "nested_tuple = ((1, 2), (3, 4), (5, 6))\n", + "\n", + "# Access elements of a nested tuple\n", + "print(\"Element at row 2, column 1:\", nested_tuple[1][0])" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ClxVjrpxu50c", + "outputId": "2f62b675-f9af-4501-bde8-68f3f878330a" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "The first element is: 1\n", + "The second element is: apple\n", + "3.14 is in the tuple\n", + "Tuple elements:\n", + "1\n", + "apple\n", + "3.14\n", + "True\n", + "Element at row 2, column 1: 3\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "The above program begins by creating a tuple named my_tuple and accesses the elements of the tuple using index positions. The first element (1) is accessed with my_tuple[0], and the second element (\"apple\") is accessed with my_tuple[1].\n", + "\n", + "The code also calculates the length of the tuple, checks for the presence of an element, and iterates through the tuple using a for loop. The len() function is used to find and store the length of the my_tuple tuple." + ], + "metadata": { + "id": "IGqQie05vFqS" + } + }, + { + "cell_type": "markdown", + "source": [ + "In Python, a tuple is an ordered, immutable collection of elements. Tuples are similar to lists, but the key difference is that tuples cannot be modified once they are created. They are defined using parentheses () and may contain elements of different data types. Here are some key characteristics and operations related to tuples:\n", + "\n", + "### Creating a Tuple:\n", + "You can create a tuple by enclosing a sequence of elements within parentheses." + ], + "metadata": { + "id": "zz0aSf2UkYzU" + } + }, + { + "cell_type": "code", + "source": [ + "my_tuple = (1, 2, 3, 'apple', 'banana')\n", + "empty_tuple = ()\n", + "singleton_tuple = (42,) # Note the comma for a singleton tuple\n" + ], + "metadata": { + "id": "tygro3kQkixV" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**Accessing Elements:**\n", + "\n", + "Elements in a tuple are accessed using indexing. Tuples, like lists, use zero-based indexing." + ], + "metadata": { + "id": "msL95hSrk24I" + } + }, + { + "cell_type": "code", + "source": [ + "print(my_tuple[0]) # Output: 1\n", + "print(my_tuple[3]) # Output: 'apple'\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "q7tsGRXOk7I2", + "outputId": "5fb5bc93-ae86-4d7f-8768-5b45e8a10807" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "1\n", + "apple\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**Immutable Nature:**\n", + "\n", + "Once a tuple is created, you cannot add, remove, or modify elements." + ], + "metadata": { + "id": "cLBClDk4k_2V" + } + }, + { + "cell_type": "code", + "source": [ + "my_tuple[0] = 5 # Raises TypeError: 'tuple' object does not support item assignment\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 175 + }, + "id": "JJRybcyolEwG", + "outputId": "4ee1977f-554b-41a8-db61-d477aadb3e1c" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "error", + "ename": "TypeError", + "evalue": "'tuple' object does not support item assignment", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmy_tuple\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m5\u001b[0m \u001b[0;31m# Raises TypeError: 'tuple' object does not support item assignment\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**Tuple Packing and Unpacking:**\n", + "\n", + "Tuple Packing: Assigning multiple values to a single variable creates a tuple." + ], + "metadata": { + "id": "oCME4zxolLWS" + } + }, + { + "cell_type": "code", + "source": [ + "packed_tuple = 1, 'apple', 3.14\n", + "print(packed_tuple)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "YAXQ1HCUlP9z", + "outputId": "73018811-70cc-4969-b1bf-c4f75d03947d" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "(1, 'apple', 3.14)\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**Tuple Unpacking:**\n", + "\n", + "Extracting values from a tuple and assigning them to variables." + ], + "metadata": { + "id": "l_-lCIqZlTpY" + } + }, + { + "cell_type": "code", + "source": [ + "x, y, z = packed_tuple\n", + "print(\"packed_tuple contains : \", packed_tuple)\n", + "print(\"X contains: \", x)\n", + "print(\"Y contains: \",y)\n", + "print(\"Z contains:\", z)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "KRUUBSVZlPUF", + "outputId": "f2693c9f-e54f-4031-83b3-b256b8440c62" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "packed_tuple contains : (1, 'apple', 3.14)\n", + "X contains: 1\n", + "Y contains: apple\n", + "Z contains: 3.14\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "### Tuple Methods:\n", + "Tuples have limited methods due to their immutability, but they include:\n", + "\n", + "1. **count(value):**\n", + "\n", + " Returns the number of occurrences of a value in the tuple." + ], + "metadata": { + "id": "Wh4Wvd06ldoO" + } + }, + { + "cell_type": "code", + "source": [ + "count_apple = my_tuple.count('apple')\n", + "print(count_apple)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "FEIpiBu8lr6H", + "outputId": "f385b20d-0081-4d62-b839-21584f7f9e8d" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "1\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "2. **index(value):**\n", + "\n", + " Returns the index of the first occurrence of a value." + ], + "metadata": { + "id": "7t52UC-blu8l" + } + }, + { + "cell_type": "code", + "source": [ + "index_banana = my_tuple.index('banana')\n", + "print(index_banana)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "yAQC0IgNl2b7", + "outputId": "8498fd32-835a-46c5-e37e-6c71479c9684" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "4\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**Tuple Concatenation and Repetition:**\n", + "\n", + "Tuples support concatenation using the + operator and repetition using the * operator." + ], + "metadata": { + "id": "IzrhB2HFl_-_" + } + }, + { + "cell_type": "code", + "source": [ + "tuple1 = (1, 2, 3)\n", + "tuple2 = ('apple', 'banana')\n", + "concatenated_tuple = tuple1 + tuple2 # Output: (1, 2, 3, 'apple', 'banana')\n", + "repeated_tuple = tuple1 * 2 # Output: (1, 2, 3, 1, 2, 3)\n", + "print(\"tuple1: \",tuple1)\n", + "print(\"tuple2\", tuple2)\n", + "print('concatenated_tuple', concatenated_tuple)\n", + "print(\"repeated_tuple: \", repeated_tuple)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "YPLxwoa-mDLm", + "outputId": "fe00ebe3-c141-4ffd-8f62-c24707a74330" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "tuple1: (1, 2, 3)\n", + "tuple2 ('apple', 'banana')\n", + "concatenated_tuple (1, 2, 3, 'apple', 'banana')\n", + "repeated_tuple: (1, 2, 3, 1, 2, 3)\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "**Membership Test (in):**\n", + "\n", + "Checks if a value is present in the tuple." + ], + "metadata": { + "id": "qcIstO90tfPK" + } + }, + { + "cell_type": "code", + "source": [ + "my_tuple = ('apple', 'banana', 'orange')\n", + "is_present = 'banana' in my_tuple # Returns True\n" + ], + "metadata": { + "id": "czuoIcKctluc" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "**Length (len):**\n", + "\n", + " Returns the number of elements in the tuple." + ], + "metadata": { + "id": "GOago9Citr3w" + } + }, + { + "cell_type": "code", + "source": [ + "my_tuple = (1, 2, 3, 'apple', 'banana')\n", + "length_of_tuple = len(my_tuple) # Returns 5\n" + ], + "metadata": { + "id": "XGllKLFytx_B" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "### Uses\n", + "\n", + "1. **Return Multiple Values from Functions:**\n", + "\n", + "Tuples are often used to return multiple values from a function." + ], + "metadata": { + "id": "T98ZuOeGmH35" + } + }, + { + "cell_type": "code", + "source": [ + "def get_info():\n", + " name = 'John'\n", + " age = 25\n", + " country = 'USA'\n", + " return name, age, country\n", + "\n", + "info_tuple = get_info()\n" + ], + "metadata": { + "id": "l3XA-IjSmQee" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "2. **Immutable Data Storage:**\n", + "\n", + "When you need a collection of elements that should remain constant, tuples provide immutability." + ], + "metadata": { + "id": "PuKTLidbmTfC" + } + }, + { + "cell_type": "markdown", + "source": [ + "**When to Use Tuples:**\n", + "\n", + "\n", + "Use tuples when you want an ordered collection of elements that should not be modified.\n", + "\n", + "Use tuples for data that should remain constant throughout the program.\n", + "\n", + "Use tuples when you need to return multiple values from a function.\n", + "\n", + "Tuples are a versatile and efficient data structure in Python, offering immutability and ordered storage." + ], + "metadata": { + "id": "aHGmvuwmmdEX" + } + }, + { + "cell_type": "markdown", + "source": [ + "# Differences between list tuple set and dictionary" + ], + "metadata": { + "id": "RuGg1WTev5CX" + } + }, + { + "cell_type": "markdown", + "source": [ + "### **1. Mutability**\n", + "\n", + "\n", + "Mutability refers to the ability of an object to change its state or content after its creation.\n", + "\n", + "**List:** Lists are mutable. This means that after defining a list, you can alter its content – be it changing, adding, or removing elements. The ability to modify lists makes them versatile, especially when you need a collection that will undergo various transformations during runtime.\n", + "\n", + "**Tuple:** In stark contrast, tuples are immutable. Once created, their content remains static. This fixed nature makes tuples hashable and usable as dictionary keys. They're especially suitable when you need to ensure data integrity and ensure certain values remain constant throughout a program.\n", + "\n", + "**Set:** Sets are mutable, allowing insertion and removal of elements. However, since they only house unique values, any attempt to add a duplicate value will be ignored. This makes them invaluable for tasks like deduplication.\n", + "\n", + "**Dictionary:** These are mutable, granting you the flexibility to add, remove, or change key-value pairs. However, their keys, much like tuple elements, need to be of immutable types." + ], + "metadata": { + "id": "OW3dudtWwAon" + } + }, + { + "cell_type": "markdown", + "source": [ + "### **2. Ordering**\n", + "Ordering relates to whether a data structure maintains a consistent sequence of its contained elements.\n", + "\n", + "**List:** Lists are inherently ordered. The sequence in which you insert elements into a list is preserved, allowing indexed access and modifications. This characteristic is useful for tasks like sorting or when the sequence has semantic meaning, like storing monthly sales data.\n", + "\n", + "**Tuple:** Tuples, like lists, are ordered. Even though they're immutable, the sequence they're declared in remains consistent.\n", + "\n", + "**Set:** A set doesn't retain any specific order. It’s designed for membership tests, making it optimal for scenarios where insertion order isn't significant but ensuring uniqueness is.\n", + "\n", + "**Dictionary:** In versions prior to Python 3.7, dictionaries didn't guarantee order. However, from Python 3.7 onwards, dictionaries maintain the order of items based on their insertion. This ensures a predictable mapping, beneficial for operations like serialization." + ], + "metadata": { + "id": "oq1-4m47wWWB" + } + }, + { + "cell_type": "markdown", + "source": [ + "### 3. Duplicate Handling\n", + "How a data structure handles duplicates often determines its utility in particular scenarios.\n", + "\n", + "**List:** Lists don't discriminate against duplicate values. They're accommodating structures that will store as many identical elements as you insert, which is handy for collections where occurrences matter.\n", + "\n", + "**Tuple:** Tuples also permit duplicates, offering another avenue for ordered, immutable storage.\n", + "\n", + "**Set:** Sets stand out by not allowing any duplicate values. This inherent property assists in creating collections of unique items, which can be beneficial for operations like union, intersection, and difference.\n", + "\n", + "**Dictionary:** While dictionaries allow duplicate values, their keys must be unique. This ensures a one-to-one mapping between keys and values." + ], + "metadata": { + "id": "UlozHaVHwWKC" + } + }, + { + "cell_type": "markdown", + "source": [ + "### **4. Data Structure Representation**\n", + "Understanding how each structure is represented syntactically can accelerate coding speed and reduce errors.\n", + "\n", + "**List:** Denoted by square brackets. e.g., [1, 2, 3]\n", + "\n", + "**Tuple:** Encapsulated within parentheses. e.g., (1, 2, 3)\n", + "\n", + "**Set:** Defined using curly brackets without key-value pairs. e.g., {1, 2, 3}\n", + "\n", + "**Dictionary:** Illustrated using curly brackets with distinct key-value pairs. e.g., {'a':1, 'b':2, 'c':3}\n", + "\n", + "For a streamlined understanding, consider the following table:\n", + "\n", + "\n", + "\n", + "\n", + "list ====== ( Mutable : Yes) (Ordered : Yes) (Allows Duplicates : Yes) (Unique features : - ) ( Representation : [1,2,3] )\n", + "\n", + "tuple ====== ( Mutable : No) (Ordered : Yes) ( Allows duplicates : Yes) (Unique features : can be a dictionary key) (Representaiton : ( 1, 2, 3) )\n", + "\n", + "set ====== ( Mutable : yes) (Ordered : no) ( Allows duplicates : no) (Unique features : mathematical computing) (Representaiton :\n", + "{1, 2, 3} )\n", + "\n", + "\n", + "dictionary ====== ( Mutable : yes) (Ordered : no) ( Allows duplicates : yes ( values) ) (Unique features : key-value pairs ) (Representaiton :\n", + "{'a':1, 'b':2, 'c':3} )\n", + "\n", + "\n" + ], + "metadata": { + "id": "mLelCcg4wV9Q" + } + }, + { + "cell_type": "markdown", + "source": [ + "# List comprehension" + ], + "metadata": { + "id": "WaR5qxglaJ3N" + } + }, + { + "cell_type": "markdown", + "source": [ + "new_list = [expression **for** item **in** iterable **if** condition]\n" + ], + "metadata": { + "id": "izl5R325aRD6" + } + }, + { + "cell_type": "markdown", + "source": [ + "List comprehension is a concise way to create lists in Python. It provides a more readable and compact syntax for creating lists compared to traditional for-loops. The basic structure of a list comprehension is:\n", + "\n", + "\n", + "\n", + "* expression: The operation or value to be included in the new list.\n", + "* item: Variable representing each element in the iterable.\n", + "\n", + "* iterable: The sequence or collection being iterated (e.g., list, tuple, string).\n", + "* condition: Optional. A filter that determines whether to include the item in the new list.\n" + ], + "metadata": { + "id": "Jo7V-dgdaiYr" + } + }, + { + "cell_type": "markdown", + "source": [ + "## Example 1: Squaring Numbers" + ], + "metadata": { + "id": "5wnutbPJbKFM" + } + }, + { + "cell_type": "code", + "source": [ + "# Using a for loop\n", + "numbers = [1, 2, 3, 4, 5]\n", + "squared_numbers = []\n", + "for num in numbers:\n", + " squared_numbers.append(num**2)\n", + "\n", + "# Using list comprehension\n", + "squared_numbers_comp = [num**2 for num in numbers]\n", + "\n", + "print(squared_numbers) # Output: [1, 4, 9, 16, 25]\n", + "print(squared_numbers_comp) # Output: [1, 4, 9, 16, 25]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "tGgi3C-sZ__u", + "outputId": "df712001-a6f9-4d1c-dc72-6d96b656d469" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[1, 4, 9, 16, 25]\n", + "[1, 4, 9, 16, 25]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Example 2: Filtering Even Numbers" + ], + "metadata": { + "id": "jPuYlkVxbP0r" + } + }, + { + "cell_type": "code", + "source": [ + "# Using a for loop\n", + "numbers = [1, 2, 3, 4, 5]\n", + "even_numbers = []\n", + "for num in numbers:\n", + " if num % 2 == 0:\n", + " even_numbers.append(num)\n", + "\n", + "# Using list comprehension with a condition\n", + "even_numbers_comp = [num for num in numbers if num % 2 == 0]\n", + "\n", + "print(even_numbers) # Output: [2, 4]\n", + "print(even_numbers_comp) # Output: [2, 4]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "iga5-mtdbNZt", + "outputId": "f3b06293-7d8e-48e9-c290-334f33152210" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[2, 4]\n", + "[2, 4]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Example 3: Creating Pairs" + ], + "metadata": { + "id": "o9cvz9_hbU8H" + } + }, + { + "cell_type": "code", + "source": [ + "# Using a for loop\n", + "pairs = []\n", + "for x in range(3):\n", + " for y in range(3):\n", + " pairs.append((x, y))\n", + "\n", + "# Using list comprehension with two loops\n", + "pairs_comp = [(x, y) for x in range(3) for y in range(3)]\n", + "\n", + "print(pairs) # Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n", + "print(pairs_comp) # Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n", + "\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "90LcfJnNbSQB", + "outputId": "8574e5f4-4122-4436-d247-12742b2e63a2" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n", + "[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Example 4: Using a Condition" + ], + "metadata": { + "id": "H41VzV15baF1" + } + }, + { + "cell_type": "code", + "source": [ + "# Using a for loop\n", + "numbers = [1, 2, 3, 4, 5]\n", + "squared_evens = []\n", + "for num in numbers:\n", + " if num % 2 == 0:\n", + " squared_evens.append(num**2)\n", + "\n", + "# Using list comprehension with a condition\n", + "squared_evens_comp = [num**2 for num in numbers if num % 2 == 0]\n", + "\n", + "print(squared_evens) # Output: [4, 16]\n", + "print(squared_evens_comp) # Output: [4, 16]\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "kTDrSfT8bXSo", + "outputId": "c1c1a335-f64a-4038-fc96-3e5aa6938745" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[4, 16]\n", + "[4, 16]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "# Decorators" + ], + "metadata": { + "id": "Zgmgycox2Epn" + } + }, + { + "cell_type": "markdown", + "source": [ + "\n", + "In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods. Decorators allow you to wrap a function with another function, adding additional functionality or modifying its behavior without directly modifying the source code of the function being decorated.\n", + "\n", + "Here's a basic structure of a decorator:" + ], + "metadata": { + "id": "noyipbpQ2El5" + } + }, + { + "cell_type": "code", + "source": [ + "@decorator_function\n", + "def my_function():\n", + " # Function body\n", + " pass\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 227 + }, + "id": "i9KHkaSI2KGs", + "outputId": "52645370-1fe4-42a8-886c-f80cab2f2f7d" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "error", + "ename": "NameError", + "evalue": "name 'decorator_function' is not defined", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34m@\u001b[0m\u001b[0mdecorator_function\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmy_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# Function body\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mpass\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mNameError\u001b[0m: name 'decorator_function' is not defined" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "This is equivalent to:" + ], + "metadata": { + "id": "V3Fz9Ie72EiW" + } + }, + { + "cell_type": "code", + "source": [ + "def my_function():\n", + " # Function body\n", + " pass\n", + "\n", + "my_function = decorator_function(my_function)\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 210 + }, + "id": "jgoSWJqu2Pr-", + "outputId": "dbe9636a-190e-453a-dac5-9a8f9cdb3e86" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "error", + "ename": "NameError", + "evalue": "name 'decorator_function' is not defined", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mpass\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mmy_function\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdecorator_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmy_function\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'decorator_function' is not defined" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Here's a simple example to illustrate the concept of decorators:" + ], + "metadata": { + "id": "FEswk-Vy2Edu" + } + }, + { + "cell_type": "code", + "source": [ + "# Decorator function\n", + "def my_decorator(func):\n", + " def wrapper():\n", + " print(\"Something is happening before the function is called.\")\n", + " func()\n", + " print(\"Something is happening after the function is called.\")\n", + " return wrapper\n", + "\n", + "# Using the decorator\n", + "@my_decorator\n", + "def say_hello():\n", + " print(\"Hello!\")\n", + "\n", + "# Calling the decorated function\n", + "say_hello()\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "qC6SmMl42bKE", + "outputId": "af1af49e-5121-4dc2-8b78-a8facfff5012" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Something is happening before the function is called.\n", + "Hello!\n", + "Something is happening after the function is called.\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "In this example, my_decorator is a decorator function that takes another function (func) as an argument, and it returns a new function (wrapper). The wrapper function includes additional behavior before and after calling the original function. The @my_decorator syntax is a shortcut for say_hello = my_decorator(say_hello)." + ], + "metadata": { + "id": "m0VCA2p32EYV" + } + }, + { + "cell_type": "markdown", + "source": [ + "## 1. Timing Decorator:" + ], + "metadata": { + "id": "A7kfgFqm2qel" + } + }, + { + "cell_type": "code", + "source": [ + "import time\n", + "\n", + "def timing_decorator(func):\n", + " def wrapper(*args, **kwargs):\n", + " start_time = time.time()\n", + " result = func(*args, **kwargs)\n", + " end_time = time.time()\n", + " print(f\"{func.__name__} took {end_time - start_time} seconds to run.\")\n", + " return result\n", + " return wrapper\n", + "\n", + "@timing_decorator\n", + "def slow_function():\n", + " time.sleep(2)\n", + " print(\"Function executed.\")\n", + "\n", + "slow_function()\n", + "# This decorator measures the time it takes for a function to run." + ], + "metadata": { + "id": "EjknR0_seTf5", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "702e62bc-4b38-4159-93c1-a3bd5b2f6490" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Function executed.\n", + "slow_function took 2.002241373062134 seconds to run.\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## 2. Authorization Decorator:" + ], + "metadata": { + "id": "5DYkKxvw2yTw" + } + }, + { + "cell_type": "code", + "source": [ + "def authorization_decorator(func):\n", + " def wrapper(user):\n", + " if user.is_authenticated:\n", + " return func(user)\n", + " else:\n", + " print(\"User is not authenticated.\")\n", + " # Optionally, you could redirect to a login page or perform other actions.\n", + " return wrapper\n", + "\n", + "@authorization_decorator\n", + "def view_profile(user):\n", + " print(f\"Viewing profile for {user.username}.\")\n", + "\n", + "# Assuming user is an object with an 'is_authenticated' attribute\n", + "view_profile(user)\n", + "# This decorator checks if a user is authenticated before allowing access to a protected resource." + ], + "metadata": { + "id": "PL13tTDr2uE6" + }, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Decorators are widely used in Python for tasks such as logging, memoization, access control, and more. They provide a clean and elegant way to extend the behavior of functions or methods." + ], + "metadata": { + "id": "PvtHPu-Y3ASK" + } + }, + { + "cell_type": "code", + "source": [], + "metadata": { + "id": "iSjHSQO93A__" + }, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file diff --git a/python_codes_practice.ipynb b/python_codes_practice.ipynb new file mode 100644 index 0000000..ea78bf8 --- /dev/null +++ b/python_codes_practice.ipynb @@ -0,0 +1,75 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [], + "authorship_tag": "ABX9TyPVN9LYyghhEf2sdDNzngaW", + "include_colab_link": true + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "source": [ + "Write a function where the input is an array of integer and returns the sum of all the odd numbers in the array" + ], + "metadata": { + "id": "I8MtnFMPzelU" + } + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "id": "uru_IU86yRoX", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "5801e3f7-a65d-42f5-9b6e-78288215322a" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "25\n" + ] + } + ], + "source": [ + "def sum_of_odd_numbers(arr):\n", + " return sum(num for num in arr if num % 2 != 0)\n", + "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", + "result = sum_of_odd_numbers(numbers)\n", + "print(result)\n" + ] + }, + { + "cell_type": "code", + "source": [], + "metadata": { + "id": "NxZc7Mowzj_j" + }, + "execution_count": null, + "outputs": [] + } + ] +} \ No newline at end of file