{ "cells": [ { "cell_type": "markdown", "id": "d9be6007", "metadata": {}, "source": [ "# Variables\n", "In Python, variables are used to store and manage data. Each variable has a name and a value, and the type of the variable indicates what kind of data it can hold.\n", "### Variable Naming Rules:\n", " * Variable names in Python can contain alphanumerical characters `a-z`, `A-Z`, `0-9` and some special characters such as `_`.\n", " * Normal variable names must start with a letter.\n", " * By convention, variable names start with a lower-case letter, and Class names start with a capital letter.\n", " * In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:\n", "\n", " and, as, assert, break, class, continue, def, del, elif, else, except, \n", " exec, finally, for, from, global, if, import, in, is, lambda, not, or,\n", " pass, print, raise, return, try, while, with, yield\n" ] }, { "cell_type": "markdown", "id": "736c7bab", "metadata": {}, "source": [ "## Assignment in Python\n", "The assignment operator in Python is `=`.\n", "\n", "Assigning a value to a new variable creates the variable:" ] }, { "cell_type": "code", "execution_count": null, "id": "f17cbaf7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 John True\n" ] } ], "source": [ "#Assigning values to variable\n", "x = 10\n", "name = \"rafay\"\n", "is_student = True\n", "\n", "#print the variable\n", "print(x, name, is_student)" ] }, { "cell_type": "code", "execution_count": 2, "id": "3fe322b1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your name?ali\n", "Name: ali\n" ] } ], "source": [ "#using input and output in python\n", "\n", "name= input(\"What is your name?\")\n", "print(\"Name:\", name)" ] }, { "cell_type": "markdown", "id": "f0ecf03c", "metadata": {}, "source": [ "# Operators\n", "Most operators and comparisons in Python work as one would expect:\n", "\n", "### Arithmetic operators `+`, `-`, `*`, `/`, `//` (integer division), '**' power\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "4dc5a097", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3 -1 2 3\n" ] } ], "source": [ "print (1 + 2, 1 - 2, 1 * 2, 7 // 2)" ] }, { "cell_type": "code", "execution_count": 4, "id": "8ccede4f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.0 -1.0 2.0 0.5\n" ] } ], "source": [ "print (1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0)" ] }, { "cell_type": "code", "execution_count": 5, "id": "96b9d6a0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0\n" ] } ], "source": [ "# Integer division of float numbers\n", "print (3.0 // 2.0)" ] }, { "cell_type": "code", "execution_count": 6, "id": "499597eb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.5\n" ] } ], "source": [ "# Flaot division of integers\n", "print (3/2)" ] }, { "cell_type": "code", "execution_count": 7, "id": "9082a90f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n" ] } ], "source": [ "# The power operators in python isn't ^, but **\n", "print (2 ** 2)\n" ] }, { "cell_type": "markdown", "id": "43c97990", "metadata": {}, "source": [ "Note: The `/` operator always performs a floating point division in Python 3.x.\n", "This is not true in Python 2.x, where the result of `/` is always an integer if the operands are integers.\n", "to be more specific, `1/2 = 0.5` (`float`) in Python 3.x, and `1/2 = 0` (`int`) in Python 2.x (but `1.0/2 = 0.5` in Python 2.x)." ] }, { "cell_type": "markdown", "id": "d0c64a24", "metadata": {}, "source": [ "* The boolean operators are spelled out as the words `and`, `not`, `or`." ] }, { "cell_type": "code", "execution_count": 8, "id": "c875a486", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "print (True and False)" ] }, { "cell_type": "code", "execution_count": 9, "id": "74efcd1e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "print (not False)" ] }, { "cell_type": "code", "execution_count": 10, "id": "db035d4c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "print (True or False)" ] }, { "cell_type": "markdown", "id": "4f2f3959", "metadata": {}, "source": [ "* Comparison operators `>`, `<`, `>=` (greater or equal), `<=` (less or equal), `==` equality, `is` identical." ] }, { "cell_type": "code", "execution_count": 11, "id": "4a655ee1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True False\n" ] } ], "source": [ "print (2 > 1, 2 < 1)" ] }, { "cell_type": "code", "execution_count": 12, "id": "960280fa", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True True\n" ] } ], "source": [ "print (2 >= 2, 2 <= 2)" ] }, { "cell_type": "code", "execution_count": 13, "id": "009ceee9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "# equality\n", "print ([1,2] == [1,2])" ] }, { "cell_type": "code", "execution_count": 14, "id": "414deba4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "# objects identical?\n", "l1=l2=[1,2]\n", "\n", "print (l1 is l2)" ] }, { "cell_type": "markdown", "id": "280e319e", "metadata": {}, "source": [ "# Data Types\n", "Python is a dynamically typed language, so we do not need to specify the type of a variable when we create one.\n" ] }, { "cell_type": "code", "execution_count": 15, "id": "1f3cb259", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n" ] } ], "source": [ "x=1.2\n", "print(type(x))\n", "\n", "#If we assign a new value to a variable, its type can change.\n", "x=3\n", "print(type(x))" ] }, { "cell_type": "code", "execution_count": 16, "id": "0a507159", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "#integers\n", "x = 1\n", "print (type(x))" ] }, { "cell_type": "code", "execution_count": 17, "id": "bf1a321c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# float\n", "x = 1.0\n", "print (type(x))" ] }, { "cell_type": "code", "execution_count": 18, "id": "32492b1d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# boolean\n", "b1 = True\n", "b2 = False\n", "\n", "print (type(b1))" ] }, { "cell_type": "code", "execution_count": 19, "id": "9cf80875", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# complex numbers: note the use of `j` to specify the imaginary part\n", "x = 1.0 - 1.0j\n", "print (type(x))" ] }, { "cell_type": "code", "execution_count": 20, "id": "1d1bc47e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1-1j)\n", "1.0 -1.0\n" ] } ], "source": [ "print(x)\n", "print(x.real, x.imag)" ] }, { "cell_type": "markdown", "id": "6f8f7f88", "metadata": {}, "source": [ "Check if a certain variable is integer or float...." ] }, { "cell_type": "code", "execution_count": 21, "id": "5c422cc5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "x= 5\n", "print (type(x) is int)" ] }, { "cell_type": "code", "execution_count": 22, "id": "e915abab", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "x= 5.0\n", "print (type(x) is int)" ] }, { "cell_type": "markdown", "id": "b5efd598", "metadata": {}, "source": [ "We can also use the `isinstance` method for testing types of variables:" ] }, { "cell_type": "code", "execution_count": 23, "id": "2b2880c6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "print (isinstance(x, float))" ] }, { "cell_type": "markdown", "id": "8ea12c90", "metadata": {}, "source": [ "# Type casting\n", "Typecasting in Python refers to the process of converting a variable from one data type to another. Python provides several built-in functions for typecasting. Here are some common typecasting functions:" ] }, { "cell_type": "code", "execution_count": 24, "id": "ee5598a3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "# int(x)\n", "\n", "float_num = 3.14\n", "int_num = int(float_num)\n", "print(int_num)\n" ] }, { "cell_type": "code", "execution_count": 25, "id": "a02a2e54", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.0\n" ] } ], "source": [ "# float(x)\n", "\n", "int_num = 5\n", "float_num = float(int_num)\n", "print(float_num)\n" ] }, { "cell_type": "code", "execution_count": 26, "id": "514957ba", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "# bool(x)\n", "\n", "number = 0\n", "bool_value = bool(number)\n", "print(bool_value)\n" ] }, { "cell_type": "code", "execution_count": 27, "id": "322e28b2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['h', 'e', 'l', 'l', 'o']\n" ] } ], "source": [ "#list(x)\n", "\n", "string = \"hello\"\n", "list_chars = list(string)\n", "print(list_chars)" ] }, { "cell_type": "markdown", "id": "61b6449d", "metadata": {}, "source": [ "Complex variables cannot be cast to floats or integers. We need to use `z.real` or `z.imag` to extract the part of the complex number we want:" ] }, { "cell_type": "code", "execution_count": 28, "id": "f261b3fb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.0 4\n" ] } ], "source": [ "z = 3 + 4.2j\n", "float_z= float(z.real)\n", "int_z = int(z.imag)\n", "print(float_z, int_z)" ] }, { "cell_type": "markdown", "id": "71304a89", "metadata": {}, "source": [ "# Compound data types: Strings, List and dictionaries\n", "## Strings\n", "Strings are the variable type that is used for storing text messages. " ] }, { "cell_type": "code", "execution_count": 29, "id": "c29c3b59", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "s = \"Hello world\"\n", "print (type(s))" ] }, { "cell_type": "code", "execution_count": 30, "id": "77ec8e67", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n" ] } ], "source": [ "# length of the string: the number of characters\n", "print (len(s))" ] }, { "cell_type": "code", "execution_count": 31, "id": "f7e42b91", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello test\n" ] } ], "source": [ "# replace a substring in a string with somethign else\n", "s2 = s.replace(\"world\", \"test\")\n", "print (s2)" ] }, { "cell_type": "markdown", "id": "dcc1affc", "metadata": {}, "source": [ "We can index a character in a string using `[]`:\n", "\n", "Indexing starts with 0\n", "\n", "We can extract a part of a string using the syntax `[start:stop]`, which extracts characters between index `start` and `stop` -1 (the character at index `stop` is not included):" ] }, { "cell_type": "code", "execution_count": 32, "id": "6faf3700", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "H\n" ] } ], "source": [ "print (s[0])" ] }, { "cell_type": "code", "execution_count": 33, "id": "a42f0cb6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hell\n" ] } ], "source": [ "print (s[0:4])" ] }, { "cell_type": "code", "execution_count": 34, "id": "8935ac5c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "o\n" ] } ], "source": [ "print (s[4:5])" ] }, { "cell_type": "markdown", "id": "45f6987c", "metadata": {}, "source": [ "If we omit either (or both) of `start` or `stop` from `[start:stop]`, the default is the beginning and the end of the string, respectively:" ] }, { "cell_type": "code", "execution_count": 35, "id": "e148143f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n" ] } ], "source": [ "print (s[:5])" ] }, { "cell_type": "code", "execution_count": 36, "id": "f0262e12", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "world\n" ] } ], "source": [ "print (s[6:])" ] }, { "cell_type": "code", "execution_count": 37, "id": "94c70a81", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world\n" ] } ], "source": [ "print (s[:])" ] }, { "cell_type": "markdown", "id": "8cae043b", "metadata": {}, "source": [ " We can also define the step size using the syntax `[start:end:step]` (the default value for `step` is 1, as we saw above)\n", " \n", " \n", "This technique is called *slicing*. Read more about the syntax here: http://docs.python.org/release/2.7.3/library/functions.html?highlight=slice#slice" ] }, { "cell_type": "code", "execution_count": 38, "id": "6dd4bde8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hlowrd\n", "He\n" ] } ], "source": [ "print (s[::2])\n", "print (s[:2:1])" ] }, { "cell_type": "code", "execution_count": 39, "id": "e914acdf", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "str1 str2 str3\n" ] } ], "source": [ "print (\"str1\", \"str2\", \"str3\") # The print statement concatenates strings with a space" ] }, { "cell_type": "code", "execution_count": 40, "id": "cf65e8d7", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "str1 1.0 False (-0-1j)\n" ] } ], "source": [ "print (\"str1\", 1.0, False, -1j) # The print statements converts all arguments to strings" ] }, { "cell_type": "code", "execution_count": 41, "id": "1ced3e89", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "str1str2str3\n" ] } ], "source": [ "print (\"str1\" + \"str2\" + \"str3\") # strings added with + are concatenated without space" ] }, { "cell_type": "markdown", "id": "ed451e26", "metadata": {}, "source": [ "## Lists\n", "In Python, lists are mutable, commonly used to store collection of items.\n", "\n", "Lists contain comma separated values within square brackets `[]`:\n", "\n", "Elements in a list do not all have to be of the same type\n" ] }, { "cell_type": "code", "execution_count": 42, "id": "8cc70b96", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['apple']" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_list = [1, 2, 3, 'apple', 'orange']\n", "my_list =['apple']\n", "my_list" ] }, { "cell_type": "markdown", "id": "83421420", "metadata": {}, "source": [ "Python lists can be inhomogeneous and arbitrarily nested:" ] }, { "cell_type": "code", "execution_count": 43, "id": "0685822d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1,\n", " [2,\n", " 3,\n", " [4,\n", " 5,\n", " [6, 7, 8, [9, [10, 11, [12, 13, [14, [15, [16]], [23]]], [22]]], [21]]],\n", " [20]],\n", " [19]]" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k=[1,2.2,3,'a']\n", "k=[1,[2,3,[4,5,[6,7,8,[9,[10,11,[12,13,[14,[15,[16]],[23]]],[22]]],[21]]],[20]],[19]]\n", "k" ] }, { "cell_type": "markdown", "id": "3dc3f384", "metadata": {}, "source": [ "There are a number of convenient functions for generating lists of various types, for example the `range` function:\n", "\n", " in python 3 \"range\" generates an interator, which can be converted to a list using 'list(...)'.\n", " It has no effect in python 2\n" ] }, { "cell_type": "code", "execution_count": 45, "id": "9b3ee3d4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1,\n", " 3,\n", " 5,\n", " 7,\n", " 9,\n", " 11,\n", " 13,\n", " 15,\n", " 17,\n", " 19,\n", " 21,\n", " 23,\n", " 25,\n", " 27,\n", " 29,\n", " 31,\n", " 33,\n", " 35,\n", " 37,\n", " 39,\n", " 41,\n", " 43,\n", " 45,\n", " 47,\n", " 49,\n", " 51,\n", " 53,\n", " 55,\n", " 57,\n", " 59,\n", " 61,\n", " 63,\n", " 65,\n", " 67,\n", " 69,\n", " 71,\n", " 73,\n", " 75,\n", " 77,\n", " 79,\n", " 81,\n", " 83,\n", " 85,\n", " 87,\n", " 89,\n", " 91,\n", " 93,\n", " 95,\n", " 97,\n", " 99]" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#print list(range(start, stop, step))\n", "list(range(1,100,2))" ] }, { "cell_type": "code", "execution_count": 47, "id": "9a1a1d14", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "print (list(range(-10, 10)))" ] }, { "cell_type": "code", "execution_count": 49, "id": "0590772d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Peshawar'" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#different list operations\n", "list1= [\"Lahore\", \"Karachi\", \"Peshawar\", \"Islamabad\"]\n", "\n", "#indexing\n", "list1[2]" ] }, { "cell_type": "code", "execution_count": 50, "id": "33febd53", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Karachi']" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#slicing\n", "list1[1:2]\n" ] }, { "cell_type": "code", "execution_count": 51, "id": "632913fb", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Lahore', 'Karachi', 'Peshawar', 'Islamabad', 4, 5, 6]" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Concatenation\n", "list2 = list1 + [4, 5, 6]\n", "list2" ] }, { "cell_type": "code", "execution_count": 52, "id": "e04c4d3e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Lahore',\n", " 'Karachi',\n", " 'Peshawar',\n", " 'Islamabad',\n", " 'Lahore',\n", " 'Karachi',\n", " 'Peshawar',\n", " 'Islamabad']" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Repitition\n", "repeat_list = list1 * 2\n", "repeat_list" ] }, { "cell_type": "markdown", "id": "96bd06df", "metadata": {}, "source": [ "### List Methods\n", "#### Adding, inserting, modifying, and removing elements from lists" ] }, { "cell_type": "code", "execution_count": 63, "id": "7beb2e8b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 6, 8, 9, 0, 1, 'banana']" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#add an element to the end of the list\n", "my_list = [3, 6, 8, 9, 0, 1]\n", "my_list.append('banana')\n", "my_list" ] }, { "cell_type": "code", "execution_count": 64, "id": "ed2af4bb", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 6, 8, 9, 0, 1, 'banana', 7, 8, 9]" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Extend the list by appending elements from an iterable.\n", "my_list.extend([7, 8, 9])\n", "my_list" ] }, { "cell_type": "code", "execution_count": 65, "id": "3a8236ff", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 6, 'grape', 8, 9, 0, 1, 'banana', 7, 8, 9]" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Insert an element at a specified index.\n", "my_list.insert(2, 'grape') # Insert 'grape' at index 2\n", "my_list" ] }, { "cell_type": "code", "execution_count": 66, "id": "5fa0b722", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 6, 'grape', 8, 9, 0, 1, 7, 8, 9]" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Remove the first occurrence of a specified value\n", "my_list.remove('banana')\n", "my_list" ] }, { "cell_type": "code", "execution_count": 67, "id": "2f9c99ce", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 6, 8, 9, 0, 1, 7, 8, 9]" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Removes and returns the element at a specified index.\n", "my_list.pop(2)\n", "my_list" ] }, { "cell_type": "code", "execution_count": 68, "id": "c1b50c99", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Return the index of the first occurrence of a value.\n", "index = my_list.index(6)\n", "index" ] }, { "cell_type": "code", "execution_count": 69, "id": "4e6f634b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Return the number of occurrences of a value.\n", "count_of_2 = my_list.count(2)\n", "count_of_2" ] }, { "cell_type": "code", "execution_count": 70, "id": "80d2b6ed", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 3, 6, 7, 8, 8, 9, 9]" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Sorts the list in ascending order.\n", "my_list.sort()\n", "my_list" ] }, { "cell_type": "code", "execution_count": 71, "id": "d003dade", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9, 9, 8, 8, 7, 6, 3, 1, 0]" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Reverse the order of elements in the list.\n", "my_list.reverse()\n", "my_list" ] }, { "cell_type": "code", "execution_count": 72, "id": "3a0f7451", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9, 'a', 'd', 'd', 7, 6, 3, 1, 0]" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#list can also be modified by assigning the values at specific index\n", "my_list[1:4]= ['a', 'd', 'd']\n", "my_list" ] }, { "cell_type": "markdown", "id": "42fb862a", "metadata": {}, "source": [ "## Tuple\n", "Tuples are like lists, except that they cannot be modified once created, that is they are *immutable*. \n", "\n", "In Python, tuples are created using the syntax `(..., ..., ...)`, or even `..., ...`:" ] }, { "cell_type": "code", "execution_count": 74, "id": "5273ebdf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3, 'apple', 'orange')" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#creating a tuple\n", "my_tuple = (1, 2, 3, 'apple', 'orange')\n", "my_tuple" ] }, { "cell_type": "code", "execution_count": 75, "id": "f5cc6bda", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "first_element = my_tuple[0] # Access the first element\n", "first_element" ] }, { "cell_type": "code", "execution_count": 76, "id": "a7eee4af", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3, 'apple', 'orange', 4, 5, 6)" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ " # concatenate a tuple\n", "new_tuple = my_tuple + (4, 5, 6)\n", "new_tuple" ] }, { "cell_type": "code", "execution_count": 77, "id": "d4c6836d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3, 'apple', 'orange', 1, 2, 3, 'apple', 'orange')" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# repeat a tuple using * operator\n", "repeated_tuple = my_tuple * 2\n", "repeated_tuple" ] }, { "cell_type": "code", "execution_count": 78, "id": "fc1e669f", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'tuple' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Input \u001b[1;32mIn [78]\u001b[0m, in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# tuples are immutable so u cant modify it\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m my_tuple[\u001b[38;5;241m1\u001b[39m] \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m11\u001b[39m\n", "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } ], "source": [ "# tuples are immutable so u cant modify it\n", "#modifying a tuple would result in error\n", "my_tuple[1] = 11" ] }, { "cell_type": "code", "execution_count": 80, "id": "997cb5f0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(10, 20) \n" ] } ], "source": [ "point = 10, 20\n", "\n", "print (point, type(point))" ] }, { "cell_type": "markdown", "id": "e2ae0783", "metadata": {}, "source": [ "# Dictionaries\n", "In Python, a dictionary is a collection type that allows you to store key-value pairs. Dictionaries are also known as associative arrays, hash maps, or hash tables in other programming languages. They are defined by enclosing comma-separated key-value pairs within curly braces {}" ] }, { "cell_type": "code", "execution_count": 81, "id": "0cca9c25", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n", "my_dict" ] }, { "cell_type": "code", "execution_count": 87, "id": "664db423", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Ali': [2.7, 'B+'], 'Ahmad': [3.1, 'A'], 'Zain': [3.4, 'A']}" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict = {\n", " 'Ali': [2.7, \"B+\"],\n", " 'Ahmad': [3.1, \"A\"],\n", " \"Zain\": [3.4, \"A\"]\n", "}\n", "my_dict" ] }, { "cell_type": "code", "execution_count": 88, "id": "661e601b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2.7, 'B+']" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#accessing an element using key value\n", "my_dict['Ali']" ] }, { "cell_type": "code", "execution_count": 90, "id": "a6b07ecf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Ali': [2.7, 'B+'],\n", " 'Ahmad': [3.1, 'A'],\n", " 'Zain': [3.4, 'A'],\n", " 'Ayesha': [4.0, 'A+']}" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict['Ayesha'] = [4.0, \"A+\"] # Add a new entry\n", "my_dict" ] }, { "cell_type": "code", "execution_count": 91, "id": "87d36f4e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Ali': [2.3, 'C+'],\n", " 'Ahmad': [3.1, 'A'],\n", " 'Zain': [3.4, 'A'],\n", " 'Ayesha': [4.0, 'A+']}" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_dict['Ali'] = [2.3, \"C+\"] # Modify an existing entry\n", "my_dict" ] }, { "cell_type": "code", "execution_count": 92, "id": "324d4f24", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Ali': [2.3, 'C+'], 'Zain': [3.4, 'A'], 'Ayesha': [4.0, 'A+']}" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "del my_dict['Ahmad'] # Remove the entry with key \n", "my_dict" ] }, { "cell_type": "code", "execution_count": 93, "id": "360a3779", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['Ali', 'Zain', 'Ayesha'])" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Return a view of all keys in the dictionary.\n", "my_dict.keys()\n" ] }, { "cell_type": "code", "execution_count": 94, "id": "8d4022d3", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_values([[2.3, 'C+'], [3.4, 'A'], [4.0, 'A+']])" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Returns a view of all values in the dictionary.\n", "my_dict.values()\n" ] }, { "cell_type": "code", "execution_count": 96, "id": "7397cd93", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_items([('Ali', [2.3, 'C+']), ('Zain', [3.4, 'A']), ('Ayesha', [4.0, 'A+'])])" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Returns a view of all key-value pairs as tuples.\n", "my_dict.items()" ] }, { "cell_type": "markdown", "id": "30e7fa96", "metadata": {}, "source": [ "# Sets\n", "In Python, a set is an unordered and mutable collection of unique elements. Sets are defined by enclosing comma-separated values within curly braces {}. Here are some key characteristics and examples of sets in Python:\n", "### Key Characteristics:\n", "#### Uniqueness:\n", "\n", "Sets only allow unique elements. If you try to add a duplicate element, it will not be added.\n", "#### Unordered:\n", "\n", "Sets are unordered, meaning the elements do not have a specific order.\n", "#### Mutability:\n", "\n", "Sets are mutable, so you can add or remove elements after the set is created.\n", "### Creating Sets:\n", "You can create a set using the following syntax:" ] }, { "cell_type": "code", "execution_count": 97, "id": "f955e645", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5}" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_set = {1, 2, 3, 4, 5}\n", "my_set" ] }, { "cell_type": "code", "execution_count": 99, "id": "4c8de147", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5, 6}" ] }, "execution_count": 99, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#You can add elements to a set using the add() method.\n", "my_set.add(6)\n", "my_set" ] }, { "cell_type": "code", "execution_count": 100, "id": "05bb1e10", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 4, 5, 6}" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#You can remove elements using the remove() or discard() methods.\n", "my_set.remove(3)\n", "my_set" ] }, { "cell_type": "code", "execution_count": 114, "id": "bec000ac", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "set()" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Removes all elements from the set\n", "my_set.clear()\n", "my_set" ] }, { "cell_type": "code", "execution_count": 115, "id": "ea745432", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5}" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#You can perform a union of two sets using the union() method or the | operator.\n", "set1 = {1, 2, 3}\n", "set2 = {3, 4, 5}\n", "union_set = set1.union(set2)\n", "union_set" ] }, { "cell_type": "code", "execution_count": 116, "id": "23b956c5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3}" ] }, "execution_count": 116, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#You can perform an intersection of two sets using the intersection() method or the & operator.\n", "intersection_set = set1.intersection(set2)\n", "intersection_set" ] }, { "cell_type": "code", "execution_count": 117, "id": "90449f5b", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2}" ] }, "execution_count": 117, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#You can find the difference between two sets using the difference() method or the - operator.\n", "difference_set = set1.difference(set2)\n", "difference_set" ] }, { "cell_type": "code", "execution_count": 118, "id": "3edda799", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 4, 5}" ] }, "execution_count": 118, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# You can find the symmetric difference between two sets using the symmetric_difference() method or the ^ operator.\n", "symmetric_difference_set = set1.symmetric_difference(set2)\n", "symmetric_difference_set" ] }, { "cell_type": "code", "execution_count": 120, "id": "39ab8750", "metadata": {}, "outputs": [], "source": [ "set1.add(4)\n", "set1.add(5)" ] }, { "cell_type": "code", "execution_count": 121, "id": "240f7a53", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 121, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subset = set1.issubset(set2)\n", "subset" ] }, { "cell_type": "code", "execution_count": 122, "id": "831460d0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "superset = set1.issuperset(set2)\n", "superset" ] }, { "cell_type": "code", "execution_count": null, "id": "5538bceb", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.12" } }, "nbformat": 4, "nbformat_minor": 5 }