├── CS2001_Ch12-Pandas.ipynb ├── CS2001_Ch13-FileHandling_Exceptions_OS_Pickling.ipynb ├── CS2001_Lec1.pdf ├── CS2001_Lec10-Matplotlib.ipynb ├── CS2001_Lec11-Numpy.ipynb ├── CS2001_Lec2.pdf ├── CS2001_Lec3.pdf ├── CS2001_Lec4-List.ipynb ├── CS2001_Lec5-tuples.ipynb ├── CS2001_Lec6-set.ipynb ├── CS2001_Lec7-Dictionary.ipynb ├── CS2001_Lec8-Functions and Modules-Part-I.ipynb ├── CS2001_Lec9-Functions and Modules-Part-II.ipynb ├── Matplotlib_Notebooks_fromManju_Mam ├── .ipynb_checkpoints │ ├── Matplotlib_Barchart-checkpoint.ipynb │ ├── Matplotlib_First-checkpoint.ipynb │ ├── Matplotlib_Piechart-checkpoint.ipynb │ └── Matplotlib_Subplots-checkpoint.ipynb ├── Matplotlib_Barchart.ipynb ├── Matplotlib_First.ipynb ├── Matplotlib_Piechart.ipynb └── Matplotlib_Subplots.ipynb ├── Numpy_ArrayDtypes_from_ManjuMam.ipynb ├── Numpy_Python_Cheat_Sheet.pdf ├── Pandas_Cheat_Sheet.pdf ├── README.md ├── Student-talks ├── Dictionary_Anubhav-1026.ipynb └── Introduction-to-Sets-in-Python-Arjun23-1055.pptx ├── beginners_python_cheat_sheet_pcc_all.pdf └── data └── titanic.csv /CS2001_Ch13-FileHandling_Exceptions_OS_Pickling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "5efc1c00", 6 | "metadata": {}, 7 | "source": [ 8 | "# File Operations in PYTHON\n", 9 | "\n", 10 | "File operations involve **reading data** from and **writing data** to files stored on a computer. \n", 11 | "Python provides support for handling files, making it easy to work with data stored outside the program." 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "id": "de1c0e8f", 17 | "metadata": {}, 18 | "source": [ 19 | "## 1. Introduction \n", 20 | "\n", 21 | "File Input/Output (I/O) operations allow you to store data in a file and retrieve it later.\n", 22 | "\n", 23 | "- **File Types**:\n", 24 | " 1. **Text files**:\n", 25 | " * Store data in human-readable text format.\n", 26 | " * These store data as plain text, which can be read and edited using any text editor. Examples: `.txt`, `.csv`, `.json`.\n", 27 | " * This is the default mode if no specific mode is mentioned.\n", 28 | " * Data is handled as strings (`str` in Python).\n", 29 | "\n", 30 | " 2. **Binary files**:\n", 31 | " * These store data in binary format (0s and 1s), which is not human-readable.\n", 32 | " * Examples: Images, videos, executable files (.exe), serialized data (.bin).\n", 33 | " * More compact and efficient than text files but require special software or libraries to interpret.\n", 34 | " * You must specify `b` in the mode (e.g., `rb`, `wb`).\n", 35 | " * Data is handled as `bytes` objects.\n", 36 | "\n", 37 | "\n", 38 | "\n", 39 | "- **Python File Handling Features**\n", 40 | "\n", 41 | " * **Built-in Functions:** Python offers native methods to `open`, `read`, `write`, and `close` files.\n", 42 | " * **Cross-Platform Compatibility:** Code for file operations in Python works across operating systems (Windows, Linux, macOS).\n", 43 | " * **Flexible Modes:** Choose between reading (r), writing (w), appending (a), or working with binary data (b).\n", 44 | " - **File Modes**:\n", 45 | " - `'r'` : Read\n", 46 | " - `'w'` : Write\n", 47 | " - `'a'` : Append\n", 48 | " - `'b'` : Binary mode\n", 49 | " * **Error Handling:** Python provides comprehensive error-handling mechanisms to manage file-related exceptions.\n", 50 | "\n", 51 | "\n", 52 | "\n", 53 | "* **File Path:**\n", 54 | " - **Absolute Path:** Complete path to the file (e.g., `C:/Users/Tyson/Documents/data.txt`).\n", 55 | " - **Relative Path:** Path relative to the current working directory (e.g., `data.txt`).\n", 56 | "\n", 57 | "* **Resource Management:**\n", 58 | " - It is crucial to close files after operations to free system resources.\n", 59 | " - Python's `with` statement simplifies this process by automatically managing resources." 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "id": "c012b644", 65 | "metadata": {}, 66 | "source": [ 67 | "## 2. Text File Operations\n", 68 | "Python provides several ways to interact with text files.\n", 69 | "\n", 70 | "### Basic Text File Operations\n", 71 | "\n", 72 | "Opening and Closing Files \n", 73 | "\n", 74 | "**Syntax:**\n", 75 | "```python\n", 76 | "file = open(filename, mode)\n", 77 | "file.close()\n", 78 | "\n", 79 | "Modes:\n", 80 | "'r': Read (default)\n", 81 | "'w': Write\n", 82 | "'a': Append\n", 83 | "'b': Binary\n", 84 | "'x': Create\n", 85 | "'+': Read and write\n", 86 | "\n" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": 2, 92 | "id": "1d27954f-4ae1-4116-b62b-fa9d7087b2e1", 93 | "metadata": {}, 94 | "outputs": [ 95 | { 96 | "name": "stdout", 97 | "output_type": "stream", 98 | "text": [ 99 | "Hello, Python File Operations!\n" 100 | ] 101 | } 102 | ], 103 | "source": [ 104 | "file = open(\"example.txt\", \"w\") # Open file in write mode\n", 105 | "file.write(\"Hello, Python File Operations!\") # Write to file\n", 106 | "file.close() # Close file\n", 107 | "\n", 108 | "# Reading from the same file\n", 109 | "file = open(\"example.txt\", \"r\") # Open file in read mode\n", 110 | "content = file.read() # Read file contents\n", 111 | "print(content) # Output: Hello, Python File Operations!\n", 112 | "file.close() # Close file" 113 | ] 114 | }, 115 | { 116 | "cell_type": "markdown", 117 | "id": "c7fd5e7d-6467-40c3-99f5-a7169f996ef6", 118 | "metadata": {}, 119 | "source": [ 120 | "## **3. Working with `with` Statement**\n", 121 | "The `with` statement in Python simplifies file operations by automatically managing resources such as file handles. \n", 122 | "\n", 123 | "It ensures that the file is properly closed once the block of code is exited, even if an exception occurs during file operations.\n", 124 | "\n", 125 | "**Syntax:**\n", 126 | "```python\n", 127 | "with open(filename, mode) as file_object:\n", 128 | " # Perform file operations\n", 129 | "```\n", 130 | "\n", 131 | "* `filename`: The name (and path) of the file to open.\n", 132 | "* `mode`: The mode in which the file is opened (e.g., 'r', 'w', 'a', etc.).\n", 133 | "* `file_object`: A temporary variable representing the opened file.\n" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": 3, 139 | "id": "fe062eca", 140 | "metadata": {}, 141 | "outputs": [ 142 | { 143 | "name": "stdout", 144 | "output_type": "stream", 145 | "text": [ 146 | "File Content: Hello, World!\n", 147 | "Python File Operations\n" 148 | ] 149 | } 150 | ], 151 | "source": [ 152 | "file_path = 'sample.txt'\n", 153 | "\n", 154 | "# Writing to a text file\n", 155 | "with open(file_path, 'w') as file:\n", 156 | " file.write('Hello, World!\\n')\n", 157 | " file.write('Python File Operations')\n", 158 | "\n", 159 | "# Reading from a text file\n", 160 | "with open(file_path, 'r') as file:\n", 161 | " content = file.read()\n", 162 | " print('File Content:', content)" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "id": "a3f61580-920d-42c6-9223-3bd4b059ec33", 168 | "metadata": {}, 169 | "source": [ 170 | "### File Read and Write Methods" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": 14, 176 | "id": "527f8f63-a1c4-4457-815e-8693cf5aaf29", 177 | "metadata": {}, 178 | "outputs": [ 179 | { 180 | "name": "stdout", 181 | "output_type": "stream", 182 | "text": [ 183 | "Using read():\n", 184 | "Line 1: Hello, World!\n", 185 | "Line 2: Python File Operations.\n", 186 | "Line 3: End of File.\n", 187 | "\n", 188 | "\n", 189 | "Using readline():\n", 190 | "Line 1: Hello, World!\n", 191 | "\n", 192 | "Using readlines():\n", 193 | "['Line 2: Python File Operations.\\n', 'Line 3: End of File.\\n']\n", 194 | "\n", 195 | "Final content of the file:\n", 196 | "Line 1: Hello, World!\n", 197 | "Line 2: Python File Operations.\n", 198 | "Line 3: End of File.\n", 199 | "Line 4: This is a new line added using write().\n", 200 | "Line 5: Another line using writelines().\n", 201 | "Line 6: Last line of the file.\n", 202 | "\n" 203 | ] 204 | } 205 | ], 206 | "source": [ 207 | "# Create a sample file with some initial content\n", 208 | "with open(\"sample.txt\", \"w\") as file:\n", 209 | " file.write(\"Line 1: Hello, World!\\n\")\n", 210 | " file.write(\"Line 2: Python File Operations.\\n\")\n", 211 | " file.write(\"Line 3: End of File.\\n\")\n", 212 | "\n", 213 | "# Demonstrating file read and write methods\n", 214 | "with open(\"sample.txt\", \"r+\") as file: # Open for both reading and writing\n", 215 | " # Using read() to read the entire file\n", 216 | " print(\"Using read():\")\n", 217 | " print(file.read())\n", 218 | " \n", 219 | " # Moving the cursor back to the beginning\n", 220 | " file.seek(0)\n", 221 | " \n", 222 | " # Using readline() to read the first line\n", 223 | " print(\"\\nUsing readline():\")\n", 224 | " print(file.readline().strip()) # .strip() removes trailing newlines\n", 225 | " \n", 226 | " # Using readlines() to read the remaining lines into a list\n", 227 | " print(\"\\nUsing readlines():\")\n", 228 | " print(file.readlines())\n", 229 | " \n", 230 | " # Moving the cursor back to the end of the file\n", 231 | " file.seek(0, 2) # 2 indicates the end of the file\n", 232 | " \n", 233 | " # Using write() to append a new line\n", 234 | " file.write(\"Line 4: This is a new line added using write().\\n\")\n", 235 | " \n", 236 | " # Using writelines() to add multiple lines\n", 237 | " file.writelines([\n", 238 | " \"Line 5: Another line using writelines().\\n\",\n", 239 | " \"Line 6: Last line of the file.\\n\"\n", 240 | " ])\n", 241 | "\n", 242 | "# Verifying the final file content\n", 243 | "print(\"\\nFinal content of the file:\")\n", 244 | "with open(\"sample.txt\", \"r\") as file:\n", 245 | " print(file.read())\n" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "id": "7e01b7db-f500-467b-8a51-c28e64073dcb", 251 | "metadata": {}, 252 | "source": [ 253 | "| **Method** | **Description** | **Usage** |\n", 254 | "|-------------------|---------------------------------------------------------------------------------|----------------------------------------|\n", 255 | "| `read()` | Reads the entire file content as a single string. | `file.read()` |\n", 256 | "| `readline()` | Reads one line at a time. | `file.readline()` |\n", 257 | "| `readlines()` | Reads all lines of the file into a list of strings. | `file.readlines()` |\n", 258 | "| `write()` | Writes a single string to the file. | `file.write(\"text\")` |\n", 259 | "| `writelines()` | Writes a list of strings to the file (each string should already include `\\n`).| `file.writelines([\"line1\\n\", \"line2\"])`|\n", 260 | "| `seek(offset, where)` | Moves the cursor to a specific byte position in the file. | `file.seek(0)` to reset to the start. `where`: 0 (default): Start of the file. 1: Current position of the cursor. 2: End of the file. |\n", 261 | "| `tell()` | Returns the current position of the cursor in the file. | `file.tell()` |\n" 262 | ] 263 | }, 264 | { 265 | "cell_type": "markdown", 266 | "id": "b10d147a-cafd-4c0a-9cfc-1e169a64974b", 267 | "metadata": {}, 268 | "source": [ 269 | "**HW:** Find out `truncate()` in file operation?" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "id": "75075457", 275 | "metadata": {}, 276 | "source": [ 277 | "## 4. Binary File Operations\n", 278 | "Binary files store data in binary (0s and 1s). To work with binary files, use binary mode.\n", 279 | "\n", 280 | "```python\n", 281 | "\n", 282 | "```\n" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": 34, 288 | "id": "c02942d5-bc04-43b2-9b6a-a2ac537ee7c5", 289 | "metadata": {}, 290 | "outputs": [ 291 | { 292 | "name": "stdout", 293 | "output_type": "stream", 294 | "text": [ 295 | "b'This is binary data'\n" 296 | ] 297 | } 298 | ], 299 | "source": [ 300 | "# Writing binary data\n", 301 | "with open('binary_file.bin', 'wb') as file:\n", 302 | " file.write(b'This is binary data')\n", 303 | "\n", 304 | "# Reading binary data\n", 305 | "with open('binary_file.bin', 'rb') as file:\n", 306 | " data = file.read()\n", 307 | " print(data)" 308 | ] 309 | }, 310 | { 311 | "cell_type": "markdown", 312 | "id": "be1a0897", 313 | "metadata": {}, 314 | "source": [ 315 | "## 5. CSV File Operations\n", 316 | "CSV (Comma Separated Values) files are commonly used for tabular data.\n", 317 | "We can read/write CSV files using the `csv` module or `pandas`.\n", 318 | "\n", 319 | "### Using the `csv` Module" 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "execution_count": 20, 325 | "id": "9eb1d224", 326 | "metadata": {}, 327 | "outputs": [ 328 | { 329 | "name": "stdout", 330 | "output_type": "stream", 331 | "text": [ 332 | "['Name', 'Age', 'City']\n", 333 | "['Kartik', '21', 'Gorakhpur']\n", 334 | "['Nikhil', '22', 'Benares']\n" 335 | ] 336 | } 337 | ], 338 | "source": [ 339 | "import csv\n", 340 | "\n", 341 | "# Writing to a CSV file\n", 342 | "with open('data.csv', 'w', newline='') as file:\n", 343 | " writer = csv.writer(file)\n", 344 | " writer.writerow(['Name', 'Age', 'City'])\n", 345 | " writer.writerow(['Kartik', 21, 'Gorakhpur'])\n", 346 | " writer.writerow(['Nikhil', 22, 'Benares'])\n", 347 | "\n", 348 | "# Reading from a CSV file\n", 349 | "with open('data.csv', 'r') as file:\n", 350 | " reader = csv.reader(file)\n", 351 | " for row in reader:\n", 352 | " print(row)" 353 | ] 354 | }, 355 | { 356 | "cell_type": "code", 357 | "execution_count": 17, 358 | "id": "76f43f6e-fcea-4d1c-b91b-bd2bb3aab53a", 359 | "metadata": {}, 360 | "outputs": [ 361 | { 362 | "data": { 363 | "text/plain": [ 364 | "\u001b[1;31mDocstring:\u001b[0m\n", 365 | "writerow(iterable)\n", 366 | "\n", 367 | "Construct and write a CSV record from an iterable of fields. Non-string\n", 368 | "elements will be converted to string.\n", 369 | "\u001b[1;31mType:\u001b[0m builtin_function_or_method" 370 | ] 371 | }, 372 | "metadata": {}, 373 | "output_type": "display_data" 374 | } 375 | ], 376 | "source": [ 377 | "writer.writerow?" 378 | ] 379 | }, 380 | { 381 | "cell_type": "markdown", 382 | "id": "95e53dd5", 383 | "metadata": {}, 384 | "source": [ 385 | "### Using `pandas` for CSV Files\n", 386 | "Using `pandas` is often more convenient for complex CSV files." 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 19, 392 | "id": "25cc0344", 393 | "metadata": {}, 394 | "outputs": [ 395 | { 396 | "name": "stdout", 397 | "output_type": "stream", 398 | "text": [ 399 | " Name Age City\n", 400 | "0 Alok 20 Rajgir\n", 401 | "1 Ujjwal 21 Patna\n" 402 | ] 403 | } 404 | ], 405 | "source": [ 406 | "import pandas as pd\n", 407 | "\n", 408 | "# Writing to CSV with pandas\n", 409 | "df = pd.DataFrame({\n", 410 | " 'Name': ['Alok', 'Ujjwal'],\n", 411 | " 'Age': [20, 21],\n", 412 | " 'City': ['Rajgir', 'Patna']\n", 413 | "})\n", 414 | "df.to_csv('data_pandas.csv', index=False)\n", 415 | "\n", 416 | "# Reading from CSV with pandas\n", 417 | "df = pd.read_csv('data_pandas.csv')\n", 418 | "print(df)" 419 | ] 420 | }, 421 | { 422 | "cell_type": "markdown", 423 | "id": "ecb1230d-6e11-4d39-a7f7-bd618edaec27", 424 | "metadata": {}, 425 | "source": [ 426 | "## File exceptions handling" 427 | ] 428 | }, 429 | { 430 | "cell_type": "markdown", 431 | "id": "cf245580-fc71-4536-9cdc-a81748017281", 432 | "metadata": {}, 433 | "source": [ 434 | "When working with files, you might encounter errors or exceptions. \n", 435 | "For instance, trying to `open` a `file` that **doesn’t exist** or **attempting to write to a read-only file** can cause your program to crash. \n", 436 | "\n", 437 | "To prevent this, Python provides mechanisms to handle file-related exceptions gracefully. \n", 438 | "\n", 439 | "**Common Exceptions are:**\n" 440 | ] 441 | }, 442 | { 443 | "cell_type": "markdown", 444 | "id": "45a710f1-22c0-43c4-b687-814b2a822187", 445 | "metadata": {}, 446 | "source": [ 447 | "| **Exception** | **Description** |\n", 448 | "|-----------------------|---------------------------------------------------------------------------------|\n", 449 | "| `FileNotFoundError` | Raised when trying to access a file that does not exist. |\n", 450 | "| `PermissionError` | Raised when attempting an operation without sufficient permissions. |\n", 451 | "| `IsADirectoryError` | Raised when a directory is treated as a file. |\n", 452 | "| `IOError` | General exception for input/output errors. |\n", 453 | "| `EOFError` | Raised when trying to read beyond the end of a file. |\n" 454 | ] 455 | }, 456 | { 457 | "cell_type": "markdown", 458 | "id": "2f47dbae-e2e4-48e1-ba35-ea2bf45b5a71", 459 | "metadata": {}, 460 | "source": [ 461 | "#### Using `try-except` for Error Handling\n", 462 | "\n", 463 | "use try-except blocks to catch and handle file-related exceptions. This ensures your program doesn't crash unexpectedly and can respond appropriately to errors." 464 | ] 465 | }, 466 | { 467 | "cell_type": "code", 468 | "execution_count": 21, 469 | "id": "f11868e8-e68e-4be2-8024-469be67d2873", 470 | "metadata": {}, 471 | "outputs": [ 472 | { 473 | "name": "stdout", 474 | "output_type": "stream", 475 | "text": [ 476 | "Error: The file does not exist.\n" 477 | ] 478 | } 479 | ], 480 | "source": [ 481 | "try:\n", 482 | " # Attempt to open a file that doesn't exist\n", 483 | " with open(\"nonexistent_file.txt\", \"r\") as file:\n", 484 | " content = file.read()\n", 485 | "except FileNotFoundError:\n", 486 | " print(\"Error: The file does not exist.\")\n" 487 | ] 488 | }, 489 | { 490 | "cell_type": "markdown", 491 | "id": "5724ad6d-ba03-4234-bd8b-709c800a8aeb", 492 | "metadata": {}, 493 | "source": [ 494 | "#### Handling multiple exceptions" 495 | ] 496 | }, 497 | { 498 | "cell_type": "code", 499 | "execution_count": 22, 500 | "id": "07699d0e-89ca-42c2-8754-5e8324c4e53a", 501 | "metadata": {}, 502 | "outputs": [ 503 | { 504 | "name": "stdout", 505 | "output_type": "stream", 506 | "text": [ 507 | "Error: File not found.\n" 508 | ] 509 | } 510 | ], 511 | "source": [ 512 | "try:\n", 513 | " # Trying to read from a file\n", 514 | " with open(\"examplee.txt\", \"r\") as file:\n", 515 | " print(file.read())\n", 516 | "except FileNotFoundError:\n", 517 | " print(\"Error: File not found.\")\n", 518 | "except PermissionError:\n", 519 | " print(\"Error: You do not have the necessary permissions.\")\n", 520 | "except IOError as e:\n", 521 | " print(f\"An I/O error occurred: {e}\")\n" 522 | ] 523 | }, 524 | { 525 | "cell_type": "markdown", 526 | "id": "bbf1389e-ffcf-407a-9ab7-69f5b79efc47", 527 | "metadata": {}, 528 | "source": [ 529 | "#### Using `else` and `finally`\n", 530 | "`else:` Executes if no exception occurs.\n", 531 | "\n", 532 | "\n", 533 | "`finally:` Always executes, used for cleanup tasks like closing a file." 534 | ] 535 | }, 536 | { 537 | "cell_type": "code", 538 | "execution_count": 23, 539 | "id": "e6a21528-3260-4723-ab04-173e2315bf96", 540 | "metadata": {}, 541 | "outputs": [ 542 | { 543 | "name": "stdout", 544 | "output_type": "stream", 545 | "text": [ 546 | "File content successfully read:\n", 547 | "Hello, Python File Operations!\n", 548 | "File operation completed.\n" 549 | ] 550 | } 551 | ], 552 | "source": [ 553 | "try:\n", 554 | " with open(\"example.txt\", \"r\") as file:\n", 555 | " content = file.read()\n", 556 | "except FileNotFoundError:\n", 557 | " print(\"Error: File not found.\")\n", 558 | "else:\n", 559 | " print(\"File content successfully read:\")\n", 560 | " print(content)\n", 561 | "finally:\n", 562 | " print(\"File operation completed.\")\n" 563 | ] 564 | }, 565 | { 566 | "cell_type": "markdown", 567 | "id": "89fc84d4-8221-4af2-9984-44ecf832fe21", 568 | "metadata": {}, 569 | "source": [ 570 | "----------------" 571 | ] 572 | }, 573 | { 574 | "cell_type": "markdown", 575 | "id": "c2ceec8c", 576 | "metadata": {}, 577 | "source": [ 578 | "# Exception Handling\n", 579 | "\n", 580 | "Exception handling in Python allows you to manage errors gracefully without crashing your program. It ensures that even when unexpected issues occur, your code can recover or provide useful feedback to the user.\n", 581 | "\n", 582 | "**Key points to remember:**\n", 583 | "\n", 584 | "* `Exceptions:` Errors detected during program execution (e.g., ZeroDivisionError, FileNotFoundError).\n", 585 | "* `try Block:` Contains code that might raise an exception.\n", 586 | "* `except Block:` Handles specific or general exceptions if they occur.\n", 587 | "* `else Block:` Executes if no exception is raised.\n", 588 | "* `finally Block:` Executes regardless of whether an exception occurred, often used for cleanup.\n", 589 | "\n", 590 | "\n", 591 | "**Syntax:**\n", 592 | "```python\n", 593 | "try:\n", 594 | " # Code that might raise an exception\n", 595 | "except ExceptionType:\n", 596 | " # Code to handle the exception\n", 597 | "else:\n", 598 | " # Optional: Executes if no exception occurs\n", 599 | "finally:\n", 600 | " # Optional: Executes always\n", 601 | "```" 602 | ] 603 | }, 604 | { 605 | "cell_type": "markdown", 606 | "id": "954b2aab-3cf8-4601-b881-7e15262d36d8", 607 | "metadata": {}, 608 | "source": [ 609 | "### Summary table of common exceptions in Python:\n", 610 | "\n", 611 | "| **Exception** | **Description** |\n", 612 | "|--------------------------|---------------------------------------------------------------------------------|\n", 613 | "| `ArithmeticError` | Base class for errors in numeric operations. |\n", 614 | "| `ZeroDivisionError` | Raised when dividing by zero. |\n", 615 | "| `ValueError` | Raised when a function receives an argument of the right type but an invalid value. |\n", 616 | "| `TypeError` | Raised when an operation or function is applied to an object of inappropriate type. |\n", 617 | "| `IndexError` | Raised when trying to access an element outside the range of a sequence. |\n", 618 | "| `KeyError` | Raised when a key is not found in a dictionary. |\n", 619 | "| `FileNotFoundError` | Raised when a file or directory is requested but does not exist. |\n", 620 | "| `IOError` | Raised when an I/O operation fails (e.g., file not readable). |\n", 621 | "| `PermissionError` | Raised when a file operation is denied due to insufficient permissions. |\n", 622 | "| `NameError` | Raised when a variable or function name is not found in the local/global scope.|\n", 623 | "| `AttributeError` | Raised when an invalid attribute is accessed on an object. |\n", 624 | "| `ImportError` | Raised when an import statement fails to find the module. |\n", 625 | "| `ModuleNotFoundError` | Subclass of `ImportError`, raised when the module is not found. |\n", 626 | "| `StopIteration` | Raised by an iterator when it has no more items. |\n", 627 | "| `OverflowError` | Raised when a numerical operation exceeds the limits of a numeric type. |\n", 628 | "| `MemoryError` | Raised when an operation runs out of memory. |\n", 629 | "| `EOFError` | Raised when the `input()` function hits an end-of-file condition. |\n", 630 | "| `RuntimeError` | Raised when an error is detected that doesn't fall into any specific category.|\n", 631 | "| `AssertionError` | Raised when an `assert` statement fails. |\n", 632 | "| `SyntaxError` | Raised when Python encounters a syntax error in the code. |\n", 633 | "| `IndentationError` | Raised when the indentation is incorrect. |\n", 634 | "| `KeyboardInterrupt` | Raised when the user interrupts program execution (e.g., Ctrl+C). |\n", 635 | "| `SystemExit` | Raised when the `sys.exit()` function is called. |\n", 636 | "\n", 637 | "---\n", 638 | "\n", 639 | "## **Notes:**\n", 640 | "- **Hierarchy**: Many exceptions inherit from a base class like `Exception` or `BaseException`.\n", 641 | "- **Custom Exceptions**: You can define your own exceptions by subclassing `Exception`.\n", 642 | "\n", 643 | "For detailed information, refer to the [Python documentation](https://docs.python.org/3/library/exceptions.html).\n" 644 | ] 645 | }, 646 | { 647 | "cell_type": "markdown", 648 | "id": "706423cf-d458-47af-9ee4-dafb7e43276c", 649 | "metadata": {}, 650 | "source": [ 651 | "### Example: Handling a Single Exception" 652 | ] 653 | }, 654 | { 655 | "cell_type": "code", 656 | "execution_count": 24, 657 | "id": "f9ba346f", 658 | "metadata": {}, 659 | "outputs": [ 660 | { 661 | "name": "stdout", 662 | "output_type": "stream", 663 | "text": [ 664 | "Error: Cannot divide by zero\n" 665 | ] 666 | } 667 | ], 668 | "source": [ 669 | "try:\n", 670 | " result = 10 / 0\n", 671 | "except ZeroDivisionError:\n", 672 | " print('Error: Cannot divide by zero')" 673 | ] 674 | }, 675 | { 676 | "cell_type": "markdown", 677 | "id": "bc096ba6", 678 | "metadata": {}, 679 | "source": [ 680 | "### Handling Multiple Exceptions" 681 | ] 682 | }, 683 | { 684 | "cell_type": "code", 685 | "execution_count": 25, 686 | "id": "02817ebc", 687 | "metadata": {}, 688 | "outputs": [ 689 | { 690 | "name": "stdout", 691 | "output_type": "stream", 692 | "text": [ 693 | "Error: File not found\n" 694 | ] 695 | } 696 | ], 697 | "source": [ 698 | "try:\n", 699 | " file = open('non_existent_file.txt', 'r')\n", 700 | " result = 10 / 0\n", 701 | "except FileNotFoundError:\n", 702 | " print('Error: File not found')\n", 703 | "except ZeroDivisionError:\n", 704 | " print('Error: Cannot divide by zero')" 705 | ] 706 | }, 707 | { 708 | "cell_type": "markdown", 709 | "id": "c969f6c0-b004-45a3-92e4-61b644bcfde6", 710 | "metadata": {}, 711 | "source": [ 712 | "### General Exception Handing" 713 | ] 714 | }, 715 | { 716 | "cell_type": "code", 717 | "execution_count": 26, 718 | "id": "b46a96b0-605c-4c25-89e0-dace51b6cd59", 719 | "metadata": {}, 720 | "outputs": [ 721 | { 722 | "name": "stdout", 723 | "output_type": "stream", 724 | "text": [ 725 | "An error occurred: division by zero\n" 726 | ] 727 | } 728 | ], 729 | "source": [ 730 | "try:\n", 731 | " result = 10 / 0\n", 732 | "except Exception as e:\n", 733 | " print(f\"An error occurred: {e}\")\n" 734 | ] 735 | }, 736 | { 737 | "cell_type": "markdown", 738 | "id": "8cee2ad4", 739 | "metadata": {}, 740 | "source": [ 741 | "# Exercises\n", 742 | "Practice problems to reinforce your understanding:\n", 743 | "\n", 744 | "1. Write a function to count the occurrences of each word in a text file.\n", 745 | "2. Write a program to read a CSV file and print the average of a numeric column.\n", 746 | "3. Handle exceptions for a program that opens a file, reads an integer from it, and divides 100 by that integer.\n" 747 | ] 748 | }, 749 | { 750 | "cell_type": "markdown", 751 | "id": "706de5fd-c372-4678-b68d-cd6329ff196f", 752 | "metadata": {}, 753 | "source": [ 754 | "----" 755 | ] 756 | }, 757 | { 758 | "cell_type": "markdown", 759 | "id": "8ae2db56-1cb5-4a4f-a83c-761b01579a9c", 760 | "metadata": {}, 761 | "source": [ 762 | "# Working with Directories in Python\n", 763 | "\n", 764 | "The `os` module in Python provides functions to interact with the operating system, including creating, removing, and managing directories." 765 | ] 766 | }, 767 | { 768 | "cell_type": "code", 769 | "execution_count": 27, 770 | "id": "0291d424-0e4b-446f-a4f5-095653767066", 771 | "metadata": {}, 772 | "outputs": [ 773 | { 774 | "name": "stdout", 775 | "output_type": "stream", 776 | "text": [ 777 | "Current Directory: D:\\Teaching-related\\CS2001-2101 (Python)\\Demos\n" 778 | ] 779 | } 780 | ], 781 | "source": [ 782 | "import os\n", 783 | "\n", 784 | "# Get current working directory\n", 785 | "current_directory = os.getcwd()\n", 786 | "print(f\"Current Directory: {current_directory}\")\n" 787 | ] 788 | }, 789 | { 790 | "cell_type": "code", 791 | "execution_count": 28, 792 | "id": "32bc807b-47ab-4b4d-9695-7674884ecc53", 793 | "metadata": {}, 794 | "outputs": [ 795 | { 796 | "name": "stdout", 797 | "output_type": "stream", 798 | "text": [ 799 | "Files and Directories in current directory: ['.ipynb_checkpoints', '.vscode', 'abs.py', 'AI_ML_Basics.ipynb', 'anatomy.png', 'CS2001-Matplotlob.ipynb', 'CS2001_Ch12-Pandas.ipynb', 'CS2001_Lec10-Matplotlib.ipynb', 'CS2001_Lec11-Numpy.ipynb', 'CS2001_Lec4-List.ipynb', 'CS2001_Lec5-tuples.ipynb', 'CS2001_Lec6-set.ipynb', 'CS2001_Lec7-Dictionary.ipynb', 'CS2001_Lec8-Functions and Modules-Part-I.ipynb', 'CS2001_Lec9-Functions and Modules-Part-II.ipynb', 'data', 'data.csv', 'data_pandas.csv', 'Detailed_NumPy_Notebook.ipynb', 'example.txt', 'filename.npy', 'matplotlib-tutorial-for-beginners.ipynb', 'my_module.py', 'new_file.csv', 'Numpy_Comprehensive_Guide.ipynb', 'NumPy_Theoretical_Concepts.ipynb', 'Pandas_Lecture_Content.ipynb', 'plot1.png', 'Python_File_Operations_and_Exception_Handling.ipynb', 'RD SIr.ipynb', 'sample.txt', 'saved_plot.png', 'Sec-A', 'Sec-C', 'SecB', 'test.ipynb', 'test.py', 'Untitled.ipynb', '__pycache__']\n" 800 | ] 801 | } 802 | ], 803 | "source": [ 804 | "# List files and directories in the current directory\n", 805 | "entries = os.listdir()\n", 806 | "print(\"Files and Directories in current directory:\", entries)" 807 | ] 808 | }, 809 | { 810 | "cell_type": "markdown", 811 | "id": "4ea21778-03b0-4703-8f27-4dff245b1cc6", 812 | "metadata": {}, 813 | "source": [ 814 | "```python\n", 815 | "# Create a new directory\n", 816 | "os.mkdir(\"new_directory\")\n", 817 | "\n", 818 | "# Remove an empty directory\n", 819 | "os.rmdir(\"new_directory\")\n", 820 | "print(\"Directory 'new_directory' removed.\")\n", 821 | "\n", 822 | "\n", 823 | "# Rename a directory\n", 824 | "os.rename(\"old_directory\", \"renamed_directory\")\n", 825 | "print(\"Directory renamed from 'old_directory' to 'renamed_directory'.\")\n", 826 | "```" 827 | ] 828 | }, 829 | { 830 | "cell_type": "markdown", 831 | "id": "31484281-bfa7-498e-8e96-b60e51476e15", 832 | "metadata": {}, 833 | "source": [ 834 | "---------------" 835 | ] 836 | }, 837 | { 838 | "cell_type": "markdown", 839 | "id": "706884a3-7128-4f8c-95a6-5219103d071f", 840 | "metadata": {}, 841 | "source": [ 842 | "# `Pickle` Module\n", 843 | "\n", 844 | "The `pickle` module in Python is used for serializing (pickling) and deserializing (unpickling) Python objects. \n", 845 | "* **Serialization** is the process of converting an object into a `byte stream`, which can be saved to a file or transferred over a network.\n", 846 | "* **Deserialization** is the reverse process, where the `byte stream` is converted back into a Python object.\n", 847 | "\n", 848 | "A **byte** stream is a sequence of bytes, which are the smallest unit of data in computing. It represents data in a raw binary format, allowing for the efficient storage, transmission, and manipulation of data.\n", 849 | "\n", 850 | "\n", 851 | "**Important methods:**\n", 852 | "\n", 853 | "\n", 854 | "* `pickle.dump(obj, file)`: Serializes an object and writes it to a file. \n", 855 | "* `pickle.load(file)`: Deserializes the content of a file and returns the object. \n", 856 | "* `pickle.dumps(obj)`: Serializes an object and returns a byte stream (useful when not writing to a file). \n", 857 | "* `pickle.loads(bytes)`: Deserializes a byte stream and returns the objec\n", 858 | "\n", 859 | "\n", 860 | "**Why Use pickle?**\n", 861 | " * **Data Persistence:** You can save Python objects (e.g., complex data structures, machine learning models) to a file for later use.\n", 862 | " * **Object Transmission:** Useful for transferring Python objects over a network.\n", 863 | "\n", 864 | "**Application** \n", 865 | "One common real-world application of the pickle module is in saving and loading machine learning models. \n", 866 | "When you train a model, the training process can take a lot of time and computational resources. Instead of retraining the model every time, you can serialize (pickle) the trained model and deserialize (unpickle) it when needed.\n" 867 | ] 868 | }, 869 | { 870 | "cell_type": "markdown", 871 | "id": "4f733157-033e-449b-ba82-0f7a656ea312", 872 | "metadata": {}, 873 | "source": [ 874 | "**Pickling (Saving an Object to a File)**" 875 | ] 876 | }, 877 | { 878 | "cell_type": "code", 879 | "execution_count": 29, 880 | "id": "051bbb32-48f1-44ae-b889-cd47fd6725d1", 881 | "metadata": {}, 882 | "outputs": [ 883 | { 884 | "name": "stdout", 885 | "output_type": "stream", 886 | "text": [ 887 | "Data has been pickled and saved to 'data.pkl'\n" 888 | ] 889 | } 890 | ], 891 | "source": [ 892 | "import pickle\n", 893 | "\n", 894 | "# Sample data (Python dictionary)\n", 895 | "data = {'name': 'Anuj', 'age': 60, 'city': 'Ranchi'}\n", 896 | "\n", 897 | "# Serialize the data and save it to a file\n", 898 | "with open('data.pkl', 'wb') as file:\n", 899 | " pickle.dump(data, file)\n", 900 | "\n", 901 | "print(\"Data has been pickled and saved to 'data.pkl'\")" 902 | ] 903 | }, 904 | { 905 | "cell_type": "markdown", 906 | "id": "ed4cda2b-44b0-4959-a9a9-6047e5214407", 907 | "metadata": {}, 908 | "source": [ 909 | "**Unpickling (Loading an Object from a File)**\n" 910 | ] 911 | }, 912 | { 913 | "cell_type": "code", 914 | "execution_count": 30, 915 | "id": "ac75b05b-6f75-4fe0-8f27-3234480909ab", 916 | "metadata": {}, 917 | "outputs": [ 918 | { 919 | "name": "stdout", 920 | "output_type": "stream", 921 | "text": [ 922 | "Loaded data: {'name': 'Anuj', 'age': 60, 'city': 'Ranchi'}\n" 923 | ] 924 | } 925 | ], 926 | "source": [ 927 | "# Deserialize the data from the file\n", 928 | "with open('data.pkl', 'rb') as file:\n", 929 | " loaded_data = pickle.load(file)\n", 930 | "\n", 931 | "print(\"Loaded data:\", loaded_data)" 932 | ] 933 | }, 934 | { 935 | "cell_type": "markdown", 936 | "id": "de02ddf2-8fdc-4d9d-aed5-b521b4dc7159", 937 | "metadata": {}, 938 | "source": [ 939 | "**We can also **serialize** and **deserialize** objects without involving files, using `dumps()` and `loads()`.**" 940 | ] 941 | }, 942 | { 943 | "cell_type": "code", 944 | "execution_count": 31, 945 | "id": "2404bb7c-b3a3-486d-90f5-5845717520b8", 946 | "metadata": {}, 947 | "outputs": [ 948 | { 949 | "name": "stdout", 950 | "output_type": "stream", 951 | "text": [ 952 | "Serialized byte data: b'\\x80\\x04\\x950\\x00\\x00\\x00\\x00\\x00\\x00\\x00}\\x94(\\x8c\\x04name\\x94\\x8c\\x05Aaloo\\x94\\x8c\\x03age\\x94K\\x19\\x8c\\x04city\\x94\\x8c\\nsubziMandi\\x94u.'\n", 953 | "Deserialized data: {'name': 'Aaloo', 'age': 25, 'city': 'subziMandi'}\n" 954 | ] 955 | } 956 | ], 957 | "source": [ 958 | "data = {'name': 'Aaloo', 'age': 25, 'city': 'subziMandi'}\n", 959 | "\n", 960 | "# Serialize the object into a byte stream\n", 961 | "byte_data = pickle.dumps(data)\n", 962 | "print(\"Serialized byte data:\", byte_data)\n", 963 | "\n", 964 | "# Deserialize the byte stream back into the original object\n", 965 | "loaded_data = pickle.loads(byte_data)\n", 966 | "print(\"Deserialized data:\", loaded_data)" 967 | ] 968 | }, 969 | { 970 | "cell_type": "markdown", 971 | "id": "1c4057df-a945-4d3a-88ed-65ecf37f9448", 972 | "metadata": {}, 973 | "source": [ 974 | "# ---------------- **Thank You**------------------------" 975 | ] 976 | } 977 | ], 978 | "metadata": { 979 | "kernelspec": { 980 | "display_name": "Python 3 (ipykernel)", 981 | "language": "python", 982 | "name": "python3" 983 | }, 984 | "language_info": { 985 | "codemirror_mode": { 986 | "name": "ipython", 987 | "version": 3 988 | }, 989 | "file_extension": ".py", 990 | "mimetype": "text/x-python", 991 | "name": "python", 992 | "nbconvert_exporter": "python", 993 | "pygments_lexer": "ipython3", 994 | "version": "3.12.7" 995 | } 996 | }, 997 | "nbformat": 4, 998 | "nbformat_minor": 5 999 | } 1000 | -------------------------------------------------------------------------------- /CS2001_Lec1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IIIT-Ranchi-CS2001/lectureNotes/1834dd48b44512bab9c99c162235e25c424c9dc7/CS2001_Lec1.pdf -------------------------------------------------------------------------------- /CS2001_Lec2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IIIT-Ranchi-CS2001/lectureNotes/1834dd48b44512bab9c99c162235e25c424c9dc7/CS2001_Lec2.pdf -------------------------------------------------------------------------------- /CS2001_Lec3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IIIT-Ranchi-CS2001/lectureNotes/1834dd48b44512bab9c99c162235e25c424c9dc7/CS2001_Lec3.pdf -------------------------------------------------------------------------------- /CS2001_Lec5-tuples.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "f39d2720-633f-4442-bd61-57b913bd406e", 6 | "metadata": {}, 7 | "source": [ 8 | "# CS2001IIIT-Ranchi \n", 9 | "### *Shivang Tripathi*" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "id": "7b21aa09-47bf-45bf-81f6-eb04c73c5d62", 15 | "metadata": {}, 16 | "source": [ 17 | "# Container Type" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "id": "907ebadc-25eb-4abd-906f-49bed1aa59ad", 23 | "metadata": { 24 | "editable": true, 25 | "slideshow": { 26 | "slide_type": "" 27 | }, 28 | "tags": [] 29 | }, 30 | "source": [ 31 | "* It refers to a collection of data or objects \n", 32 | " - Can be considered as derived datatypes\n", 33 | "* Python has a wide variety of container types \n", 34 | "* Four different container types are directly available with python\n", 35 | " - **List, tuple, set, dictionary**\n", 36 | "* Many other container types are available as part of the python module “collections”\n", 37 | " - namedtuple(), ordereddict(), deque etc\n" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "id": "0793929a-3835-472e-8755-34b93031be0e", 43 | "metadata": {}, 44 | "source": [ 45 | "# Tuple" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "id": "c5cb310b-ac39-4433-a1f1-985792daf2c9", 51 | "metadata": {}, 52 | "source": [ 53 | "* A tuple is a collection data type in Python that is used to store multiple items in a single variable.\n", 54 | "* Unlike lists, tuples are immutable, meaning that once created, their elements cannot be changed.\n", 55 | "* They are useful for representing fixed collections of items and are often used when the immutability of data is needed." 56 | ] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "id": "f853c209-41d9-472f-9732-91d8501340c9", 61 | "metadata": {}, 62 | "source": [ 63 | "## Basic Properties of Tuples\n", 64 | " * ***Ordered:*** The items have a defined order, and that order will not change\n", 65 | " * ***Immutable:*** You cannot modify (add, change, or remove) elements after the tuple is created.\n", 66 | " * ***Heterogeneous:*** Tuples can store elements of different data types (integers, strings, other tuples, etc.).\n", 67 | " * ***Indexed:*** You can access elements by their index (0-based indexing)." 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "id": "1f67c3aa-ec2e-4dfb-a2e0-5677037cf243", 73 | "metadata": {}, 74 | "source": [ 75 | "## Creating a Tuple\n", 76 | "### You can create a tuple by enclosing elements in parentheses () or simply using commas." 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 4, 82 | "id": "596c9c3a-ffb5-4e3a-866e-cf82a35fb49c", 83 | "metadata": {}, 84 | "outputs": [ 85 | { 86 | "name": "stdout", 87 | "output_type": "stream", 88 | "text": [ 89 | "()\n", 90 | "(1, 2, 3, 4, 5)\n", 91 | "(1, 'apple', 3.14, True)\n", 92 | "(1, 2, 3)\n", 93 | "('A', 'N', 'I', 'L')\n" 94 | ] 95 | } 96 | ], 97 | "source": [ 98 | "# Empty tuple\n", 99 | "empty_tuple = ()\n", 100 | "print(empty_tuple)\n", 101 | "\n", 102 | "# Tuple with elements\n", 103 | "numbers = (1, 2, 3, 4, 5)\n", 104 | "mixed = (1, \"apple\", 3.14, True)\n", 105 | "print(numbers)\n", 106 | "print(mixed)\n", 107 | "\n", 108 | "# Tuple without parentheses (using commas)\n", 109 | "no_parentheses = 1, 2, 3\n", 110 | "print(no_parentheses)\n", 111 | "\n", 112 | "# Convert string or any other data type to tuple using tuple()\n", 113 | "aString = \"ANIL\"\n", 114 | "stringTotuple = tuple(aString)\n", 115 | "print(stringTotuple)" 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "id": "2e32ef2b-041a-4c6e-ba05-7769888c704b", 121 | "metadata": {}, 122 | "source": [ 123 | "## Accessing Tuple Elements\n", 124 | "### You can access elements using indexing and slicing." 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": 5, 130 | "id": "1066513c-d553-4d7e-bd89-2ed5c695b4c8", 131 | "metadata": {}, 132 | "outputs": [ 133 | { 134 | "name": "stdout", 135 | "output_type": "stream", 136 | "text": [ 137 | "10\n", 138 | "50\n", 139 | "(20, 30)\n" 140 | ] 141 | } 142 | ], 143 | "source": [ 144 | "# Access by index\n", 145 | "\n", 146 | "#-ve index:-5 -4 -3 -2 -1\n", 147 | "numbers = (10, 20, 30, 40, 50)\n", 148 | "#+ve index: 0 1 2 3 4\n", 149 | "print(numbers[0]) # Output: 10 (first element)\n", 150 | "print(numbers[-1]) # Output: 50 (last element)\n", 151 | "\n", 152 | "# Slicing\n", 153 | "sub_tuple = numbers[1:3] # Output: (20, 30)\n", 154 | "print(sub_tuple)\n" 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "id": "a4addcfb-a43c-4872-bf02-a68ed3057053", 160 | "metadata": {}, 161 | "source": [ 162 | "### Tuple Immutability\n", 163 | "##### Once a tuple is created, you cannot modify its elements (i.e., no appending, inserting, or removing elements)." 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 6, 169 | "id": "fb770c86-0931-4fee-a3ae-9b4226f9b2ff", 170 | "metadata": {}, 171 | "outputs": [ 172 | { 173 | "ename": "TypeError", 174 | "evalue": "'tuple' object does not support item assignment", 175 | "output_type": "error", 176 | "traceback": [ 177 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 178 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 179 | "Cell \u001b[1;32mIn[6], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m numbers \u001b[38;5;241m=\u001b[39m (\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m3\u001b[39m)\n\u001b[1;32m----> 2\u001b[0m \u001b[43mnumbers\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m100\u001b[39m \u001b[38;5;66;03m# This will raise a TypeError because tuples are immutable\u001b[39;00m\n", 180 | "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" 181 | ] 182 | } 183 | ], 184 | "source": [ 185 | "numbers = (1, 2, 3)\n", 186 | "numbers[0] = 100 # This will raise a TypeError because tuples are immutable" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "id": "e47d5792-8b51-4ea9-add6-166d5254205c", 192 | "metadata": {}, 193 | "source": [ 194 | "#### However, if the tuple contains mutable elements (like lists), the mutable objects inside can be changed." 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": 7, 200 | "id": "c9a15c5f-2d3d-4240-ac1d-878a8f2cf95f", 201 | "metadata": {}, 202 | "outputs": [ 203 | { 204 | "name": "stdout", 205 | "output_type": "stream", 206 | "text": [ 207 | "([100, 2], 3, 4)\n" 208 | ] 209 | } 210 | ], 211 | "source": [ 212 | "mutable_inside_tuple = ([1, 2], 3, 4)\n", 213 | "mutable_inside_tuple[0][0] = 100\n", 214 | "print(mutable_inside_tuple) # Output: ([100, 2], 3, 4)" 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "id": "6c537122-9899-4795-8e40-c6001f26dd4f", 220 | "metadata": {}, 221 | "source": [ 222 | "### Tuple Packing and Unpacking\n", 223 | "#### Packing is the process of combining multiple values into a tuple, \n", 224 | "#### and unpacking is the process of extracting the values back from the tuple." 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": 8, 230 | "id": "dd3b39bb-5787-4e44-97d1-f16c524a8a5d", 231 | "metadata": {}, 232 | "outputs": [ 233 | { 234 | "name": "stdout", 235 | "output_type": "stream", 236 | "text": [ 237 | "(1, 2, 'apple')\n", 238 | "1\n", 239 | "2\n", 240 | "apple\n" 241 | ] 242 | } 243 | ], 244 | "source": [ 245 | "# Tuple packing\n", 246 | "packed_tuple = 1, 2, \"apple\"\n", 247 | "print(packed_tuple)\n", 248 | "\n", 249 | "# tuple unpacking\n", 250 | "a, b, c = packed_tuple\n", 251 | "print(a) # Output: 1\n", 252 | "print(b) # Output: 2\n", 253 | "print(c) # Output: \"apple\"\n" 254 | ] 255 | }, 256 | { 257 | "cell_type": "markdown", 258 | "id": "404a756e-b369-496c-ba31-3967bc251a68", 259 | "metadata": {}, 260 | "source": [ 261 | "### Traversing the tuple (iterating over items of a tuple)" 262 | ] 263 | }, 264 | { 265 | "cell_type": "markdown", 266 | "id": "682f2a0d-53ae-4611-87bb-70c846879dd7", 267 | "metadata": {}, 268 | "source": [ 269 | "1. **using while loop along with len() fxn to get the length of the list**" 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": 9, 275 | "id": "90ddc0b7-94a4-44bd-b5b9-c6a8ba7c45b0", 276 | "metadata": {}, 277 | "outputs": [ 278 | { 279 | "name": "stdout", 280 | "output_type": "stream", 281 | "text": [ 282 | "Dog\n", 283 | "Cat\n", 284 | "Monkey\n", 285 | "Lion\n" 286 | ] 287 | } 288 | ], 289 | "source": [ 290 | "pets = ('Dog', 'Cat', 'Monkey', 'Lion')\n", 291 | "i = 0\n", 292 | "while i < len(pets):\n", 293 | " print(pets[i])\n", 294 | " i += 1" 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "id": "706d61df-5083-49a3-bc21-fec46660aba4", 300 | "metadata": {}, 301 | "source": [ 302 | "2. **Using *for/in* combination along with range() function**" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": 10, 308 | "id": "76ca817f-32fe-4685-834d-1f0274a6c90e", 309 | "metadata": {}, 310 | "outputs": [ 311 | { 312 | "name": "stdout", 313 | "output_type": "stream", 314 | "text": [ 315 | "Dog\n", 316 | "Cat\n", 317 | "Monkey\n", 318 | "Lion\n" 319 | ] 320 | } 321 | ], 322 | "source": [ 323 | "pets = ('Dog', 'Cat', 'Monkey', 'Lion')\n", 324 | "for i in range(len(pets)):\n", 325 | " print(pets[i])\n", 326 | " i +=1" 327 | ] 328 | }, 329 | { 330 | "cell_type": "markdown", 331 | "id": "2d645125-d889-40be-8992-19690770a130", 332 | "metadata": {}, 333 | "source": [ 334 | "3. **Using *for/in* combination treating the tuple as a collection**" 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": 12, 340 | "id": "b1c40525-274e-4430-abbe-0bfa3b7149d4", 341 | "metadata": {}, 342 | "outputs": [ 343 | { 344 | "name": "stdout", 345 | "output_type": "stream", 346 | "text": [ 347 | "\n", 348 | "Dog\n", 349 | "Cat\n", 350 | "Monkey\n", 351 | "Lion\n" 352 | ] 353 | } 354 | ], 355 | "source": [ 356 | "pets = ('Dog', 'Cat', 'Monkey', 'Lion')\n", 357 | "print(type(pets))\n", 358 | "for i in pets:\n", 359 | " print(i)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "markdown", 364 | "id": "82cb563d-59d2-48cc-91e5-ed26ac0172c0", 365 | "metadata": {}, 366 | "source": [ 367 | "4. **Iteration using enumerate()**" 368 | ] 369 | }, 370 | { 371 | "cell_type": "code", 372 | "execution_count": 13, 373 | "id": "c07b4f8b-7821-4410-b657-a4acd0612297", 374 | "metadata": {}, 375 | "outputs": [ 376 | { 377 | "name": "stdout", 378 | "output_type": "stream", 379 | "text": [ 380 | "0 Dog\n", 381 | "1 Cat\n", 382 | "2 Monkey\n", 383 | "3 Lion\n" 384 | ] 385 | } 386 | ], 387 | "source": [ 388 | "pets = ('Dog', 'Cat', 'Monkey', 'Lion')\n", 389 | "for index, pet in enumerate(pets):\n", 390 | " print(index, pet)" 391 | ] 392 | }, 393 | { 394 | "attachments": {}, 395 | "cell_type": "markdown", 396 | "id": "b53b7b31-5492-4cbf-8624-e8df66e8c571", 397 | "metadata": {}, 398 | "source": [ 399 | "### SWAPPING OF DATA\n", 400 | "* Tuple assignment can be used to swap between the data assigned to variables" 401 | ] 402 | }, 403 | { 404 | "cell_type": "code", 405 | "execution_count": 14, 406 | "id": "23a70385-c68f-406f-9710-4688d501cafc", 407 | "metadata": {}, 408 | "outputs": [ 409 | { 410 | "name": "stdout", 411 | "output_type": "stream", 412 | "text": [ 413 | "30 20\n", 414 | "30 10 20\n" 415 | ] 416 | } 417 | ], 418 | "source": [ 419 | "\n", 420 | "a, b = 20, 30\n", 421 | "a, b = b, a\n", 422 | "print(a, b)\n", 423 | "\n", 424 | "a, b, c = 10, 20, 30\n", 425 | "a, b, c = c, a, b\n", 426 | "print(a, b, c)" 427 | ] 428 | }, 429 | { 430 | "cell_type": "markdown", 431 | "id": "82fbb719-35cf-43b8-9453-fa4623ffa5bb", 432 | "metadata": {}, 433 | "source": [ 434 | "\n", 435 | "## Common Tuple Operations\n" 436 | ] 437 | }, 438 | { 439 | "cell_type": "markdown", 440 | "id": "cb689f5a-837e-47a4-bef7-c67c1c07d111", 441 | "metadata": {}, 442 | "source": [ 443 | "| Operation | Example | Description |\n", 444 | "|----------------------|---------------------|--------------------------------------------------|\n", 445 | "| **Length of tuple** | len(numbers) | Returns the number of elements in the tuple. |\n", 446 | "| **Concatenation**\t | (1, 2) + (3, 4) | Combines two tuples. |\n", 447 | "| **Repetition**\t | ('apple') * 3\t | Repeats the tuple elements. |\n", 448 | "| **Membership test** | 20 in numbers\t | Checks if an element exists in the tuple. |\n", 449 | "| **Indexing**\t | numbers[2]\t | Accesses the element at index 2. |\n", 450 | "| **Slicing**\t | numbers[1:3]\t | Extracts a subtuple from index 1 to 2. |\n", 451 | "| **Find max value**| max(numbers) | to find maximum value of a tuple |\n", 452 | "| **Find min** | min(numbers) | to find minimum |\n", 453 | "| **sum** | sum(numbers) | to find sum of all elements|\n", 454 | "| **any()** | any(numbers) | returns True if any of the tuple element is True |\n", 455 | "| **all()** | all(numbers) | returns True if all of the tuple element is True |\n", 456 | "| **sorted()**| sorted(numbers) | create a sorted version of the tuple |" 457 | ] 458 | }, 459 | { 460 | "cell_type": "code", 461 | "execution_count": 27, 462 | "id": "b7660ba2-ef52-46f1-9f6f-fc3025454a08", 463 | "metadata": {}, 464 | "outputs": [ 465 | { 466 | "name": "stdout", 467 | "output_type": "stream", 468 | "text": [ 469 | "5\n", 470 | "appleappleapple\n", 471 | "True\n", 472 | "number at index [2] is 30\n", 473 | "no. of occurence for number 30 is 1\n", 474 | "index of element 40 is 3\n", 475 | "True\n", 476 | "True\n", 477 | "150\n", 478 | "(24, 12, 4, 67, 9)\n", 479 | "[4, 9, 12, 24, 67]\n" 480 | ] 481 | } 482 | ], 483 | "source": [ 484 | "numbers = (10, 20, 30, 40, 50)\n", 485 | "print(len(numbers))\n", 486 | "print(('apple') * 3)\n", 487 | "print(20 in numbers)\n", 488 | "print(\"number at index [2] is \", numbers[2])\n", 489 | "print(\"no. of occurence for number 30 is \", numbers.count(30))\n", 490 | "print(\"index of element 40 is \", numbers.index(40))\n", 491 | "print(any(numbers))\n", 492 | "print(all(numbers))\n", 493 | "print(sum(numbers))\n", 494 | "numb = (24, 12, 4, 67, 9)\n", 495 | "sorted_numb = sorted(numb)\n", 496 | "print(numb)\n", 497 | "print(sorted_numb)" 498 | ] 499 | }, 500 | { 501 | "cell_type": "code", 502 | "execution_count": 19, 503 | "id": "92251860-10c7-46d3-85dd-1a3b76ab587b", 504 | "metadata": {}, 505 | "outputs": [ 506 | { 507 | "data": { 508 | "text/plain": [ 509 | "(10, 20, 30, 40, 50, 60, 70)" 510 | ] 511 | }, 512 | "execution_count": 19, 513 | "metadata": {}, 514 | "output_type": "execute_result" 515 | } 516 | ], 517 | "source": [ 518 | "# concatenation\n", 519 | "numbers + (60, 70)\t" 520 | ] 521 | }, 522 | { 523 | "cell_type": "code", 524 | "execution_count": 20, 525 | "id": "1319dfd6-2fcb-4f5f-9e03-c039cbf31d21", 526 | "metadata": {}, 527 | "outputs": [ 528 | { 529 | "name": "stdout", 530 | "output_type": "stream", 531 | "text": [ 532 | "True\n" 533 | ] 534 | } 535 | ], 536 | "source": [ 537 | "# Identity test\n", 538 | "num1 = (1, 2, 3)\n", 539 | "num2 = num1\n", 540 | "output = num1 is num2\n", 541 | "print(output)" 542 | ] 543 | }, 544 | { 545 | "cell_type": "markdown", 546 | "id": "a94ade16-3d2e-4f6f-84e4-5a794c22a0bb", 547 | "metadata": {}, 548 | "source": [ 549 | "------------\n", 550 | "## Tuple Methods\n", 551 | "#### Tuples have only two built-in methods due to their immutability:" 552 | ] 553 | }, 554 | { 555 | "cell_type": "markdown", 556 | "id": "e5481398-ece3-4074-b047-75ea40aeec95", 557 | "metadata": {}, 558 | "source": [ 559 | "| Method | Description | Example |\n", 560 | "|---------------------------|-----------------------------------------------------------------|-------------------------|\n", 561 | "| **count(x)** | Returns the number of times x appears in the tuple.\t | num.count(2) |\n", 562 | "| **index(x)** | Returns the index of the first occurrence of x in the tuple.|\tnum.index(2)|" 563 | ] 564 | }, 565 | { 566 | "cell_type": "code", 567 | "execution_count": 22, 568 | "id": "9a60c7ad-ba2d-4dd2-965f-942df0384c09", 569 | "metadata": {}, 570 | "outputs": [ 571 | { 572 | "name": "stdout", 573 | "output_type": "stream", 574 | "text": [ 575 | "4\n", 576 | "0\n" 577 | ] 578 | } 579 | ], 580 | "source": [ 581 | "num = (2, 1, 2, 5, 1, 2, 2, 3, 4)\n", 582 | "print(num.count(2))\n", 583 | "print(num.index(2))" 584 | ] 585 | }, 586 | { 587 | "cell_type": "markdown", 588 | "id": "0e95c389-0b43-4af5-af53-d993ae82493b", 589 | "metadata": {}, 590 | "source": [ 591 | "### Nested Tuples\n", 592 | "- Tuples can contain other tuples, making them multi-dimensional.\n", 593 | "- We could also have tuples of list, tuples of set etc." 594 | ] 595 | }, 596 | { 597 | "cell_type": "code", 598 | "execution_count": 28, 599 | "id": "13d077d3-9542-44e3-8c05-0504ebcbef5d", 600 | "metadata": {}, 601 | "outputs": [ 602 | { 603 | "name": "stdout", 604 | "output_type": "stream", 605 | "text": [ 606 | "(3, 4)\n", 607 | "3\n" 608 | ] 609 | } 610 | ], 611 | "source": [ 612 | "nested_tuple = ((1, 2), (3, 4), (5, 6))\n", 613 | "print(nested_tuple[1]) # Output: (3, 4)\n", 614 | "print(nested_tuple[1][0]) # Output: 3" 615 | ] 616 | }, 617 | { 618 | "cell_type": "code", 619 | "execution_count": 31, 620 | "id": "b289504e-4a07-4799-bd61-81699363c06c", 621 | "metadata": {}, 622 | "outputs": [ 623 | { 624 | "name": "stdout", 625 | "output_type": "stream", 626 | "text": [ 627 | "([1, 2, 3], [4, 5, 6])\n" 628 | ] 629 | } 630 | ], 631 | "source": [ 632 | "L = [1, 2, 3]\n", 633 | "L2 = [4, 5, 6]\n", 634 | "tup = L, L2\n", 635 | "print(tup)" 636 | ] 637 | }, 638 | { 639 | "cell_type": "markdown", 640 | "id": "f8092124-c57c-48b8-97c6-ccb38c431588", 641 | "metadata": {}, 642 | "source": [ 643 | "### Unpacking a Tuple\n", 644 | "- Using **\\*** operator" 645 | ] 646 | }, 647 | { 648 | "cell_type": "code", 649 | "execution_count": 33, 650 | "id": "15868e46-45da-4504-b9cb-bc24d932dc72", 651 | "metadata": {}, 652 | "outputs": [ 653 | { 654 | "name": "stdout", 655 | "output_type": "stream", 656 | "text": [ 657 | "(5, 4, (3, 2, 1), 0)\n" 658 | ] 659 | } 660 | ], 661 | "source": [ 662 | "T1 = 3, 2, 1\n", 663 | "T2 = 5, 4, T1, 0\n", 664 | "print(T2)" 665 | ] 666 | }, 667 | { 668 | "cell_type": "code", 669 | "execution_count": 34, 670 | "id": "fdf6a458-d378-4a4c-987b-db8293ed2b7c", 671 | "metadata": {}, 672 | "outputs": [ 673 | { 674 | "name": "stdout", 675 | "output_type": "stream", 676 | "text": [ 677 | "(5, 4, 3, 2, 1, 0)\n" 678 | ] 679 | } 680 | ], 681 | "source": [ 682 | "T1 = 3, 2, 1\n", 683 | "T2 = 5, 4, *T1, 0\n", 684 | "print(T2)" 685 | ] 686 | }, 687 | { 688 | "cell_type": "markdown", 689 | "id": "9e3337d4-2e56-4990-b9ce-777141292489", 690 | "metadata": {}, 691 | "source": [ 692 | "### ZIP Function\n", 693 | "- The **zip()** function in Python is used to combine multiple iterables (like lists, tuples, etc.) into a single iterable of tuples.\n", 694 | "- It pairs the elements from each iterable based on their positions.\n", 695 | "- Syntax:\n", 696 | " - zip(iterables)" 697 | ] 698 | }, 699 | { 700 | "cell_type": "code", 701 | "execution_count": 50, 702 | "id": "b871ee1f-7dad-4607-9bd9-dda76ba208d8", 703 | "metadata": {}, 704 | "outputs": [ 705 | { 706 | "name": "stdout", 707 | "output_type": "stream", 708 | "text": [ 709 | "\n", 710 | "[(1, 'a'), (2, 'b'), (3, 'c')]\n", 711 | "((1, 'a'), (2, 'b'), (3, 'c'))\n", 712 | "{1: 'a', 2: 'b', 3: 'c'}\n" 713 | ] 714 | } 715 | ], 716 | "source": [ 717 | "# Two lists of equal length\n", 718 | "list1 = [1, 2, 3]\n", 719 | "list2 = ['a', 'b', 'c']\n", 720 | "\n", 721 | "# Using zip to combine the two lists\n", 722 | "result = zip(list1, list2)\n", 723 | "print(result)\n", 724 | "print(list(result))\n", 725 | "\n", 726 | "result = zip(list1, list2)\n", 727 | "print(tuple(result))\n", 728 | "\n", 729 | "result = zip(list1, list2)\n", 730 | "print(dict(result))\n" 731 | ] 732 | }, 733 | { 734 | "cell_type": "code", 735 | "execution_count": 40, 736 | "id": "d839f83b-5642-4b22-bc49-54126df8f8f9", 737 | "metadata": {}, 738 | "outputs": [ 739 | { 740 | "name": "stdout", 741 | "output_type": "stream", 742 | "text": [ 743 | "[(1, 'a'), (2, 'b')]\n" 744 | ] 745 | } 746 | ], 747 | "source": [ 748 | "# when both lists have different lengths, it stops at the shortest iterable.\n", 749 | "list1 = [1, 2, 3]\n", 750 | "list2 = ['a', 'b']\n", 751 | "\n", 752 | "result = zip(list1, list2)\n", 753 | "print(list(result)) # Output: [(1, 'a'), (2, 'b')]" 754 | ] 755 | }, 756 | { 757 | "attachments": {}, 758 | "cell_type": "markdown", 759 | "id": "ad8b77d8-13c5-4b36-9a9c-f771cbccc005", 760 | "metadata": {}, 761 | "source": [ 762 | "### UNzipping a zipped object\n", 763 | "- You can unzip a zipped object back into separate iterables using **\\*** (the unpacking operator).\n" 764 | ] 765 | }, 766 | { 767 | "cell_type": "code", 768 | "execution_count": 2, 769 | "id": "d6a4a041-27e1-498b-96c3-d5673c2201d2", 770 | "metadata": {}, 771 | "outputs": [ 772 | { 773 | "name": "stdout", 774 | "output_type": "stream", 775 | "text": [ 776 | "(1, 2, 3)\n", 777 | "('a', 'b', 'c')\n" 778 | ] 779 | } 780 | ], 781 | "source": [ 782 | "# Zipped list\n", 783 | "zipped = [(1, 'a'), (2, 'b'), (3, 'c')]\n", 784 | "\n", 785 | "# Unzipping\n", 786 | "numbers, letters = zip(*zipped)\n", 787 | "print(numbers) # Output: (1, 2, 3)\n", 788 | "print(letters) # Output: ('a', 'b', 'c')\n" 789 | ] 790 | }, 791 | { 792 | "cell_type": "markdown", 793 | "id": "47d5faf8-5491-4507-814d-25ced7a3c20c", 794 | "metadata": {}, 795 | "source": [ 796 | "#### Zipping More Than Two Iterables\n", 797 | "- You can zip more than two iterables together. The output will contain tuples with as many elements as there are iterables." 798 | ] 799 | }, 800 | { 801 | "cell_type": "code", 802 | "execution_count": 42, 803 | "id": "4b4aca9d-68ff-4bb9-b858-788bbd26a958", 804 | "metadata": {}, 805 | "outputs": [ 806 | { 807 | "name": "stdout", 808 | "output_type": "stream", 809 | "text": [ 810 | "[(1, 'a', True), (2, 'b', False), (3, 'c', True)]\n" 811 | ] 812 | } 813 | ], 814 | "source": [ 815 | "list1 = [1, 2, 3]\n", 816 | "list2 = ['a', 'b', 'c']\n", 817 | "list3 = [True, False, True]\n", 818 | "\n", 819 | "result = zip(list1, list2, list3)\n", 820 | "print(list(result)) # Output: [(1, 'a', True), (2, 'b', False), (3, 'c', True)]\n" 821 | ] 822 | }, 823 | { 824 | "cell_type": "markdown", 825 | "id": "aa8f13c1-762a-4924-a08d-f59f6c57eb51", 826 | "metadata": {}, 827 | "source": [ 828 | "#### Using zip() with Strings\n", 829 | "- zip() works with any iterables, including strings." 830 | ] 831 | }, 832 | { 833 | "cell_type": "code", 834 | "execution_count": 43, 835 | "id": "ddbb5589-28a9-477c-9449-855859e06669", 836 | "metadata": {}, 837 | "outputs": [ 838 | { 839 | "name": "stdout", 840 | "output_type": "stream", 841 | "text": [ 842 | "[('a', '1'), ('b', '2'), ('c', '3')]\n" 843 | ] 844 | } 845 | ], 846 | "source": [ 847 | "str1 = 'abc'\n", 848 | "str2 = '123'\n", 849 | "\n", 850 | "result = zip(str1, str2)\n", 851 | "print(list(result)) " 852 | ] 853 | }, 854 | { 855 | "cell_type": "markdown", 856 | "id": "0d0995c9-7cea-4f5d-a61c-e717cbf73dca", 857 | "metadata": {}, 858 | "source": [ 859 | "#### practical applications of zip()\n", 860 | "- Creating a dictionary from two lists...\n", 861 | "- iterating over multiple list simulatenously\n", 862 | "|\n", 863 | "- Try it" 864 | ] 865 | }, 866 | { 867 | "cell_type": "code", 868 | "execution_count": 6, 869 | "id": "94483948-efac-429c-ac88-52b203d6d869", 870 | "metadata": {}, 871 | "outputs": [ 872 | { 873 | "name": "stdout", 874 | "output_type": "stream", 875 | "text": [ 876 | "{'name': 'Tarun', 'age': 20, 'city': 'Ranchi'}\n" 877 | ] 878 | } 879 | ], 880 | "source": [ 881 | "keys = ['name', 'age', 'city']\n", 882 | "values = ['Tarun', 20, 'Ranchi']\n", 883 | "\n", 884 | "# Creating a dictionary using zip\n", 885 | "dictionary = zip(keys, values)\n", 886 | "print(dict(dictionary)) # Output: {'name': 'Tarun', 'age': 20, 'city': 'Ranchi'}\n" 887 | ] 888 | }, 889 | { 890 | "cell_type": "code", 891 | "execution_count": 51, 892 | "id": "fa6f850e-3551-48d0-8e62-ee9af52a66b1", 893 | "metadata": {}, 894 | "outputs": [ 895 | { 896 | "name": "stdout", 897 | "output_type": "stream", 898 | "text": [ 899 | "1: one\n", 900 | "2: two\n", 901 | "3: three\n" 902 | ] 903 | } 904 | ], 905 | "source": [ 906 | "#Iterating Over Multiple Lists Simultaneously\n", 907 | "list1 = [1, 2, 3]\n", 908 | "list2 = ['one', 'two', 'three']\n", 909 | "\n", 910 | "# Iterating over both lists\n", 911 | "for num, word in zip(list1, list2):\n", 912 | " print(f\"{num}: {word}\")\n", 913 | " \n", 914 | "# Output:\n", 915 | "# 1: one\n", 916 | "# 2: two\n", 917 | "# 3: three\n" 918 | ] 919 | }, 920 | { 921 | "cell_type": "markdown", 922 | "id": "534a528c-4ab0-4868-b7b3-f3eb6094bcb6", 923 | "metadata": {}, 924 | "source": [ 925 | "------------" 926 | ] 927 | }, 928 | { 929 | "cell_type": "markdown", 930 | "id": "ed7e1264-833d-4dd5-8122-8ad86374ff56", 931 | "metadata": {}, 932 | "source": [ 933 | "### Partition and Join\n", 934 | "- The partition( ) **(a string method, not a tuple method)** method splits a string into three parts (basically, creates a tuple of 3 items):\n", 935 | "- the part before the specified separator,\n", 936 | "- the separator itself, and\n", 937 | "- the part after the separator." 938 | ] 939 | }, 940 | { 941 | "cell_type": "code", 942 | "execution_count": 53, 943 | "id": "aa9ae30e-08ab-4df5-8fe7-134957f2ffd6", 944 | "metadata": {}, 945 | "outputs": [ 946 | { 947 | "name": "stdout", 948 | "output_type": "stream", 949 | "text": [ 950 | "('Mera', ' ', 'IIIT Mahan')\n" 951 | ] 952 | }, 953 | { 954 | "data": { 955 | "text/plain": [ 956 | "tuple" 957 | ] 958 | }, 959 | "execution_count": 53, 960 | "metadata": {}, 961 | "output_type": "execute_result" 962 | } 963 | ], 964 | "source": [ 965 | "S1 = 'Mera IIIT Mahan'\n", 966 | "S2 = S1.partition(' ')\n", 967 | "print(S2)\n", 968 | "type(S2)" 969 | ] 970 | }, 971 | { 972 | "attachments": {}, 973 | "cell_type": "markdown", 974 | "id": "4f232775-4229-47c4-93c9-9b853eec54b7", 975 | "metadata": {}, 976 | "source": [ 977 | "### join ()\n", 978 | "- The join() method takes an iterable (like a tuple or list) and joins its elements into a single string,\n", 979 | "- separated by the specified string (often used to join characters or words)." 980 | ] 981 | }, 982 | { 983 | "cell_type": "code", 984 | "execution_count": 55, 985 | "id": "9b40efec-17c5-451f-bc56-b5ba26e31617", 986 | "metadata": {}, 987 | "outputs": [ 988 | { 989 | "name": "stdout", 990 | "output_type": "stream", 991 | "text": [ 992 | "apple-orange-banana\n" 993 | ] 994 | }, 995 | { 996 | "data": { 997 | "text/plain": [ 998 | "str" 999 | ] 1000 | }, 1001 | "execution_count": 55, 1002 | "metadata": {}, 1003 | "output_type": "execute_result" 1004 | } 1005 | ], 1006 | "source": [ 1007 | "tuple_elements = ('apple', 'orange', 'banana')\n", 1008 | "result = '-'.join(tuple_elements)\n", 1009 | "\n", 1010 | "print(result) # Output: 'apple-orange-banana'\n", 1011 | "type(result)" 1012 | ] 1013 | }, 1014 | { 1015 | "cell_type": "markdown", 1016 | "id": "684d3059-328b-4ee7-9303-3ac3b69cb5ee", 1017 | "metadata": {}, 1018 | "source": [ 1019 | "--------" 1020 | ] 1021 | }, 1022 | { 1023 | "cell_type": "markdown", 1024 | "id": "7efca0a9-3ba3-4558-8236-a787daf7f504", 1025 | "metadata": {}, 1026 | "source": [ 1027 | "### Tuple vs List\n", 1028 | "- Tuples are immutable, while lists are mutable.\n", 1029 | "- Tuples are generally faster than lists due to immutability.\n", 1030 | "- Tuples are used for read-only data, while lists are used for dynamic data.\n", 1031 | "### Advantages of Tuples\n", 1032 | "- Immutability makes them suitable for use as keys in dictionaries.\n", 1033 | "- Faster than lists because of immutability.\n", 1034 | "- They provide data integrity, ensuring that values cannot be accidentally modified." 1035 | ] 1036 | }, 1037 | { 1038 | "cell_type": "markdown", 1039 | "id": "e3c58bca-a4cf-4bee-985b-e04657f3ebec", 1040 | "metadata": {}, 1041 | "source": [ 1042 | "### Home work Exercise: Once done, copy the code in a tuple_HW.py file and upload it to your lab code repo\n", 1043 | "### Student ranking system\n", 1044 | "\n", 1045 | "* You are given two tuples:\n", 1046 | "\n", 1047 | "- students = (\"Bibek\", \"Pahul\", \"Yugraj\", \"Sonny\", \"Parnab\")\n", 1048 | "- marks = (67, 82, 91, 55, 78)\n", 1049 | "\n" 1050 | ] 1051 | }, 1052 | { 1053 | "cell_type": "markdown", 1054 | "id": "a6fdd8e0-2c0a-4c07-a47a-d88502f86e09", 1055 | "metadata": {}, 1056 | "source": [ 1057 | "#### Perform the following tasks:\n", 1058 | "\n", 1059 | "- **Combine** the students and marks into a tuple of tuples, where each tuple contains a student's name and their corresponding marks.\n", 1060 | "\n", 1061 | "- **Sort** the combined tuple by the marks in ascending order without using lambda or any custom functions.\n", 1062 | "\n", 1063 | "- **Find the highest and lowest marks** and print the corresponding students' names.\n", 1064 | "\n", 1065 | "- **Find the second-highest marks** and print the corresponding student's name.\n", 1066 | "\n", 1067 | "- **Determine how many students** scored above 75 marks." 1068 | ] 1069 | }, 1070 | { 1071 | "cell_type": "code", 1072 | "execution_count": 26, 1073 | "id": "2237ed83-77c4-4dbc-980c-cf2a3fbd7e39", 1074 | "metadata": {}, 1075 | "outputs": [ 1076 | { 1077 | "name": "stdout", 1078 | "output_type": "stream", 1079 | "text": [ 1080 | "(('pankaj', 73), ('rahul', 56), ('abhinav', 84), ('devansh', 47), ('amrit', 66))\n", 1081 | "[('devansh', 47), ('rahul', 56), ('amrit', 66), ('pankaj', 73), ('abhinav', 84)]\n", 1082 | "('devansh', 47)\n", 1083 | "('abhinav', 84)\n", 1084 | "devansh\n", 1085 | "47\n", 1086 | "('pankaj', 73)\n", 1087 | "pankaj\n" 1088 | ] 1089 | } 1090 | ], 1091 | "source": [ 1092 | "# write solution here\n", 1093 | "students =(\"pankaj\",\"rahul\",\"abhinav\",\"devansh\",\"amrit\")\n", 1094 | "marks = (73,56,84,47,66)\n", 1095 | "d = tuple(zip(students,marks))\n", 1096 | "print(d)\n", 1097 | "l=list(d)\n", 1098 | "l.sort(key=lambda x:x[1])\n", 1099 | "print(l)\n", 1100 | "print(l[0])\n", 1101 | "print(l[4])\n", 1102 | "print(l[0][0])\n", 1103 | "print(l[0][1])\n", 1104 | "print(l[3])\n", 1105 | "print(l[3][0])" 1106 | ] 1107 | }, 1108 | { 1109 | "cell_type": "code", 1110 | "execution_count": 23, 1111 | "id": "a8f45708-71e4-4e8a-a98e-a1c263635f0e", 1112 | "metadata": {}, 1113 | "outputs": [ 1114 | { 1115 | "data": { 1116 | "text/plain": [ 1117 | "[('devansh', 47),\n", 1118 | " ('rahul', 56),\n", 1119 | " ('amrit', 66),\n", 1120 | " ('pankaj', 73),\n", 1121 | " ('abhinav', 84)]" 1122 | ] 1123 | }, 1124 | "execution_count": 23, 1125 | "metadata": {}, 1126 | "output_type": "execute_result" 1127 | } 1128 | ], 1129 | "source": [ 1130 | "students =(\"pankaj\",\"rahul\",\"abhinav\",\"devansh\",\"amrit\")\n", 1131 | "marks = (73,56,84,47,66)\n", 1132 | "\n", 1133 | "comb = tuple(zip(marks, students))\n", 1134 | "nc = sorted(comb)\n", 1135 | "nl = [tuple(reversed(i)) for i in nc]\n", 1136 | "nl" 1137 | ] 1138 | }, 1139 | { 1140 | "cell_type": "markdown", 1141 | "id": "2c07715c-65b6-4a2b-b50a-033c3c379720", 1142 | "metadata": {}, 1143 | "source": [ 1144 | "##### expected output\n", 1145 | "Combined Tuple: (('Bibek', 67), ('Pahul', 82), ('Yugraj', 91), ('Sonny', 55), ('Parnab', 78)) \n", 1146 | "Sorted by Marks (Ascending): [('Sonny', 55), ('Bibek', 67), ('Parnab', 78), ('Pahul', 82), ('Yugraj', 91)] \n", 1147 | "Student with Lowest Marks: Sonny, Marks: 55 \n", 1148 | "Student with Highest Marks: Yugraj, Marks: 91 \n", 1149 | "Student with Second-Highest Marks: Pahul, Marks: 82 \n", 1150 | "Number of students scoring above 75: 3" 1151 | ] 1152 | }, 1153 | { 1154 | "cell_type": "markdown", 1155 | "id": "5806190b-1af0-4eca-917b-4b6ba385fd42", 1156 | "metadata": {}, 1157 | "source": [ 1158 | "## This should be enough for the tuples\n", 1159 | "## See ya'll in next topic: Dictionary (dict)" 1160 | ] 1161 | }, 1162 | { 1163 | "cell_type": "code", 1164 | "execution_count": 29, 1165 | "id": "90883c49-62c6-403d-ae4e-4d2b1db38841", 1166 | "metadata": {}, 1167 | "outputs": [ 1168 | { 1169 | "name": "stdout", 1170 | "output_type": "stream", 1171 | "text": [ 1172 | "1\n" 1173 | ] 1174 | } 1175 | ], 1176 | "source": [ 1177 | "print(len([i for i in nl if i[1]>75]))\n" 1178 | ] 1179 | }, 1180 | { 1181 | "cell_type": "code", 1182 | "execution_count": null, 1183 | "id": "c88e4905-5ef1-4407-89da-7bccfb48d50d", 1184 | "metadata": {}, 1185 | "outputs": [], 1186 | "source": [] 1187 | } 1188 | ], 1189 | "metadata": { 1190 | "kernelspec": { 1191 | "display_name": "Python 3 (ipykernel)", 1192 | "language": "python", 1193 | "name": "python3" 1194 | }, 1195 | "language_info": { 1196 | "codemirror_mode": { 1197 | "name": "ipython", 1198 | "version": 3 1199 | }, 1200 | "file_extension": ".py", 1201 | "mimetype": "text/x-python", 1202 | "name": "python", 1203 | "nbconvert_exporter": "python", 1204 | "pygments_lexer": "ipython3", 1205 | "version": "3.12.6" 1206 | } 1207 | }, 1208 | "nbformat": 4, 1209 | "nbformat_minor": 5 1210 | } 1211 | -------------------------------------------------------------------------------- /CS2001_Lec6-set.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "f39d2720-633f-4442-bd61-57b913bd406e", 6 | "metadata": {}, 7 | "source": [ 8 | "# CS2001IIIT-Ranchi \n", 9 | "### *Shivang Tripathi*" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "id": "7b21aa09-47bf-45bf-81f6-eb04c73c5d62", 15 | "metadata": {}, 16 | "source": [ 17 | "# Container Type" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "id": "907ebadc-25eb-4abd-906f-49bed1aa59ad", 23 | "metadata": { 24 | "editable": true, 25 | "slideshow": { 26 | "slide_type": "" 27 | }, 28 | "tags": [] 29 | }, 30 | "source": [ 31 | "* It refers to a collection of data or objects \n", 32 | " - Can be considered as derived datatypes\n", 33 | "* Python has a wide variety of container types \n", 34 | "* Four different container types are directly available with python\n", 35 | " - **List, tuple, set, dictionary**\n", 36 | "* Many other container types are available as part of the python module “collections”\n", 37 | " - namedtuple(), ordereddict(), deque etc\n" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "id": "0793929a-3835-472e-8755-34b93031be0e", 43 | "metadata": {}, 44 | "source": [ 45 | "# Set" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "id": "c5cb310b-ac39-4433-a1f1-985792daf2c9", 51 | "metadata": {}, 52 | "source": [ 53 | "* A set in Python is an **unordered** collection of **unique** elements.\n", 54 | " - meaning they have no defined position or index.\n", 55 | " - and set doesn't allow duplicate values\n", 56 | "* It is a **mutable** data structure that allows adding, removing, and performing various operations on elements.\n", 57 | "* Sets support various operations, including union, intersection, difference, and symmetric difference.\n", 58 | "* Sets are efficient for checking membership, as the average time complexity for this operation is O(1).\n", 59 | "* Sets are useful when you need to store and manipulate collections of unique items, like filtering duplicates or performing set operations.\n", 60 | "* Sets in Python provide powerful tools for handling collections of data in ways that are efficient and intuitive, especially when dealing with unique elements or performing mathematical set operations." 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "id": "f853c209-41d9-472f-9732-91d8501340c9", 66 | "metadata": {}, 67 | "source": [ 68 | "## Basic Properties of Set\n", 69 | " * ***UnOrdered:*** Elements in a set do not maintain a specific order. Thus, you cannot access elements via an index.\n", 70 | " * ***Mutable:*** While the set itself is mutable (you can add or remove elements), **the elements it contains must be immutable (like numbers, strings, or tuples)**.\n", 71 | " * ***Unique Elements:*** Sets automatically eliminate duplicate entries.\n", 72 | " * ***UnIndexed:*** There is no concept of indexing in sets since they are unordered." 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "id": "1f67c3aa-ec2e-4dfb-a2e0-5677037cf243", 78 | "metadata": {}, 79 | "source": [ 80 | "## Creating a Set\n", 81 | "### You can create a set using either curly braces { } or the set( ) constructor. \n", 82 | "#### To initialize an empty set, you must use set( ), as { } creates an empty dictionary." 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 65, 88 | "id": "596c9c3a-ffb5-4e3a-866e-cf82a35fb49c", 89 | "metadata": {}, 90 | "outputs": [ 91 | { 92 | "name": "stdout", 93 | "output_type": "stream", 94 | "text": [ 95 | "{1, 2, 3, 4, 5}\n", 96 | "set()\n", 97 | "{1, 2, 3, 4}\n", 98 | "{1, 2, 3, 4}\n", 99 | "{(1, 2), 12, 'Deepu', 23.4}\n" 100 | ] 101 | } 102 | ], 103 | "source": [ 104 | "# Creating a set with elements\n", 105 | "my_set = {1, 2, 3, 4, 5}\n", 106 | "print(my_set) # Output: {1, 2, 3, 4, 5}\n", 107 | "\n", 108 | "# Creating an empty set\n", 109 | "empty_set = set()\n", 110 | "print(empty_set) # Output: set()\n", 111 | "\n", 112 | "# Creating a set with duplicate elements (duplicates will be removed)\n", 113 | "my_set_with_duplicates = {1, 2, 2, 3, 4}\n", 114 | "print(my_set_with_duplicates) # Output: {1, 2, 3, 4}\n", 115 | "\n", 116 | "#Since sets are unordered, the elements may not appear in the same order as inserted.\n", 117 | "unorderd = {4,3,2,1}\n", 118 | "print(unorderd)\n", 119 | "\n", 120 | "# disimilar types\n", 121 | "dis_set = {\"Deepu\", 23.4, 12, (1,2)}\n", 122 | "print(dis_set)\n", 123 | "\n", 124 | "#dis_set = {\"Deepu\", 23.4, 12, (1,2), [2, 3]} #?? can't contain mutable objects\n" 125 | ] 126 | }, 127 | { 128 | "attachments": {}, 129 | "cell_type": "markdown", 130 | "id": "404a756e-b369-496c-ba31-3967bc251a68", 131 | "metadata": {}, 132 | "source": [ 133 | "### Traversing the SET (Iterations of set)" 134 | ] 135 | }, 136 | { 137 | "cell_type": "markdown", 138 | "id": "706d61df-5083-49a3-bc21-fec46660aba4", 139 | "metadata": {}, 140 | "source": [ 141 | "1. **Using *for* loop**" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": 66, 147 | "id": "76ca817f-32fe-4685-834d-1f0274a6c90e", 148 | "metadata": {}, 149 | "outputs": [ 150 | { 151 | "name": "stdout", 152 | "output_type": "stream", 153 | "text": [ 154 | "Cat\n", 155 | "Dog\n", 156 | "Lion\n", 157 | "Monkey\n" 158 | ] 159 | } 160 | ], 161 | "source": [ 162 | "pets = {'Dog', 'Cat', 'Monkey', 'Lion'}\n", 163 | "for i in pets:\n", 164 | " print(i) # order may vary" 165 | ] 166 | }, 167 | { 168 | "cell_type": "markdown", 169 | "id": "682f2a0d-53ae-4611-87bb-70c846879dd7", 170 | "metadata": {}, 171 | "source": [ 172 | "**Can we use while loop along with len() fxn to get the length of the list ???** ==> Nah" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": 67, 178 | "id": "90ddc0b7-94a4-44bd-b5b9-c6a8ba7c45b0", 179 | "metadata": {}, 180 | "outputs": [ 181 | { 182 | "ename": "TypeError", 183 | "evalue": "'set' object is not subscriptable", 184 | "output_type": "error", 185 | "traceback": [ 186 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 187 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 188 | "Cell \u001b[1;32mIn[67], line 4\u001b[0m\n\u001b[0;32m 2\u001b[0m i \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[0;32m 3\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m i \u001b[38;5;241m<\u001b[39m \u001b[38;5;28mlen\u001b[39m(pets):\n\u001b[1;32m----> 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mpets\u001b[49m\u001b[43m[\u001b[49m\u001b[43mi\u001b[49m\u001b[43m]\u001b[49m)\n\u001b[0;32m 5\u001b[0m i \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n", 189 | "\u001b[1;31mTypeError\u001b[0m: 'set' object is not subscriptable" 190 | ] 191 | } 192 | ], 193 | "source": [ 194 | "pets = {'Dog', 'Cat', 'Monkey', 'Lion'}\n", 195 | "i = 0\n", 196 | "while i < len(pets):\n", 197 | " print(pets[i])\n", 198 | " i += 1" 199 | ] 200 | }, 201 | { 202 | "cell_type": "markdown", 203 | "id": "2d645125-d889-40be-8992-19690770a130", 204 | "metadata": {}, 205 | "source": [ 206 | "**Can we Use *for/in* combination with range function???** => again Nope" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": 22, 212 | "id": "b1c40525-274e-4430-abbe-0bfa3b7149d4", 213 | "metadata": {}, 214 | "outputs": [ 215 | { 216 | "name": "stdout", 217 | "output_type": "stream", 218 | "text": [ 219 | "\n" 220 | ] 221 | }, 222 | { 223 | "ename": "TypeError", 224 | "evalue": "'set' object is not subscriptable", 225 | "output_type": "error", 226 | "traceback": [ 227 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 228 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 229 | "Cell \u001b[1;32mIn[22], line 4\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;28mtype\u001b[39m(pets))\n\u001b[0;32m 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;28mlen\u001b[39m(pets)):\n\u001b[1;32m----> 4\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mpets\u001b[49m\u001b[43m[\u001b[49m\u001b[43mi\u001b[49m\u001b[43m]\u001b[49m)\n", 230 | "\u001b[1;31mTypeError\u001b[0m: 'set' object is not subscriptable" 231 | ] 232 | } 233 | ], 234 | "source": [ 235 | "pets = {'Dog', 'Cat', 'Monkey', 'Lion'}\n", 236 | "print(type(pets))\n", 237 | "for i in range(len(pets)):\n", 238 | " print(pets[i])" 239 | ] 240 | }, 241 | { 242 | "cell_type": "markdown", 243 | "id": "82cb563d-59d2-48cc-91e5-ed26ac0172c0", 244 | "metadata": {}, 245 | "source": [ 246 | "2. **Iteration using enumerate()**" 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": 23, 252 | "id": "c07b4f8b-7821-4410-b657-a4acd0612297", 253 | "metadata": {}, 254 | "outputs": [ 255 | { 256 | "name": "stdout", 257 | "output_type": "stream", 258 | "text": [ 259 | "0 Cat\n", 260 | "1 Dog\n", 261 | "2 Lion\n", 262 | "3 Monkey\n" 263 | ] 264 | } 265 | ], 266 | "source": [ 267 | "pets = {'Dog', 'Cat', 'Monkey', 'Lion'}\n", 268 | "for index, pet in enumerate(pets):\n", 269 | " print(index, pet)" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "id": "2e32ef2b-041a-4c6e-ba05-7769888c704b", 275 | "metadata": {}, 276 | "source": [ 277 | "## Accessing SET Elements (!! CAUTION !!)\n", 278 | "### You cannot access set elements using indexing and slicing. Remember its unordered collection\n", 279 | "### you'll get error: **TypeError: 'set' object is not subscriptable**" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 25, 285 | "id": "1066513c-d553-4d7e-bd89-2ed5c695b4c8", 286 | "metadata": {}, 287 | "outputs": [ 288 | { 289 | "ename": "TypeError", 290 | "evalue": "'set' object is not subscriptable", 291 | "output_type": "error", 292 | "traceback": [ 293 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 294 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 295 | "Cell \u001b[1;32mIn[25], line 6\u001b[0m\n\u001b[0;32m 4\u001b[0m numbers \u001b[38;5;241m=\u001b[39m {\u001b[38;5;241m10\u001b[39m, \u001b[38;5;241m20\u001b[39m, \u001b[38;5;241m30\u001b[39m, \u001b[38;5;241m40\u001b[39m, \u001b[38;5;241m50\u001b[39m}\n\u001b[0;32m 5\u001b[0m \u001b[38;5;66;03m#+ve index: 0 1 2 3 4\u001b[39;00m\n\u001b[1;32m----> 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mnumbers\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m) \n", 296 | "\u001b[1;31mTypeError\u001b[0m: 'set' object is not subscriptable" 297 | ] 298 | } 299 | ], 300 | "source": [ 301 | "# Access by index\n", 302 | "\n", 303 | "#-ve index:-5 -4 -3 -2 -1\n", 304 | "numbers = {10, 20, 30, 40, 50}\n", 305 | "#+ve index: 0 1 2 3 4\n", 306 | "print(numbers[0]) " 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": 26, 312 | "id": "517a618d-bf3b-4bb2-9064-760d88279b35", 313 | "metadata": {}, 314 | "outputs": [ 315 | { 316 | "ename": "TypeError", 317 | "evalue": "'set' object is not subscriptable", 318 | "output_type": "error", 319 | "traceback": [ 320 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 321 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 322 | "Cell \u001b[1;32mIn[26], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# Slicing\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m sub_set \u001b[38;5;241m=\u001b[39m \u001b[43mnumbers\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m:\u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m]\u001b[49m\n\u001b[0;32m 3\u001b[0m \u001b[38;5;28mprint\u001b[39m(sub_set)\n", 323 | "\u001b[1;31mTypeError\u001b[0m: 'set' object is not subscriptable" 324 | ] 325 | } 326 | ], 327 | "source": [ 328 | "# Slicing\n", 329 | "sub_set = numbers[1:3]\n", 330 | "print(sub_set)" 331 | ] 332 | }, 333 | { 334 | "cell_type": "markdown", 335 | "id": "82fbb719-35cf-43b8-9453-fa4623ffa5bb", 336 | "metadata": {}, 337 | "source": [ 338 | "\n", 339 | "## SET Operations\n" 340 | ] 341 | }, 342 | { 343 | "cell_type": "markdown", 344 | "id": "18310bdc-4b92-4a16-8864-f94df6fcb5d9", 345 | "metadata": {}, 346 | "source": [ 347 | "* Python sets support several useful operations, such as **union, intersection, difference,** and more.\n", 348 | "* These are analogous to mathematical set operations." 349 | ] 350 | }, 351 | { 352 | "cell_type": "markdown", 353 | "id": "62d9126b-207e-441f-a6bf-0ecc1109f4cb", 354 | "metadata": {}, 355 | "source": [ 356 | "#### 1. Adding Elements to a Set:\n", 357 | "##### You can add elements to a set using the **add( ) or update( )** methods.\n", 358 | "\n", 359 | "* **add( ):** Adds a single element.\n", 360 | "* **update( ):** Adds multiple elements from another iterable (like a list or set)." 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": 33, 366 | "id": "b7660ba2-ef52-46f1-9f6f-fc3025454a08", 367 | "metadata": {}, 368 | "outputs": [ 369 | { 370 | "name": "stdout", 371 | "output_type": "stream", 372 | "text": [ 373 | "{1, 2, 3, 4}\n", 374 | "{1, 2, 3, 4, 5, 6, 7}\n" 375 | ] 376 | } 377 | ], 378 | "source": [ 379 | "my_set = {1, 2, 3}\n", 380 | "my_set.add(4) # Add a single element\n", 381 | "print(my_set) # Output: {1, 2, 3, 4}\n", 382 | "\n", 383 | "my_set.update([5, 6, 7]) # Add multiple elements\n", 384 | "print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}\n" 385 | ] 386 | }, 387 | { 388 | "cell_type": "markdown", 389 | "id": "4f10c6b9-9681-4d97-afff-418b31cf378c", 390 | "metadata": {}, 391 | "source": [ 392 | "#### 2. Removing Elements from a Set:\n", 393 | "##### You can remove elements from a set using **remove(), discard(), or pop()**.\n", 394 | "\n", 395 | "* **remove():** Removes an element, but raises an error if the element is not present.\n", 396 | "* **discard():** Removes an element, but does not raise an error if the element is not found.\n", 397 | "* **pop():** Removes a random element from the set, since the set is unordered." 398 | ] 399 | }, 400 | { 401 | "cell_type": "code", 402 | "execution_count": 34, 403 | "id": "92251860-10c7-46d3-85dd-1a3b76ab587b", 404 | "metadata": {}, 405 | "outputs": [ 406 | { 407 | "name": "stdout", 408 | "output_type": "stream", 409 | "text": [ 410 | "{1, 2, 4}\n", 411 | "{1, 4}\n", 412 | "{1, 4}\n", 413 | "{4}\n" 414 | ] 415 | } 416 | ], 417 | "source": [ 418 | "my_set = {1, 2, 3, 4}\n", 419 | "\n", 420 | "my_set.remove(3) # Removes 3\n", 421 | "print(my_set) # Output: {1, 2, 4}\n", 422 | "\n", 423 | "my_set.discard(2) # Removes 2\n", 424 | "print(my_set) # Output: {1, 4}\n", 425 | "\n", 426 | "my_set.discard(10) # No error if 10 is not found\n", 427 | "print(my_set) # Output: {1, 4}\n", 428 | "\n", 429 | "my_set.pop() # Removes a random element\n", 430 | "print(my_set) # Output might be {4} or {1}, depending on the random removal\n" 431 | ] 432 | }, 433 | { 434 | "cell_type": "markdown", 435 | "id": "e979ceaa-7f18-4fbf-8950-53db309cd2b1", 436 | "metadata": {}, 437 | "source": [ 438 | "#### 3. Set Union ( **|** or **union( )**):\n", 439 | "##### The union of two sets combines all elements from both sets, with duplicates removed." 440 | ] 441 | }, 442 | { 443 | "cell_type": "code", 444 | "execution_count": 35, 445 | "id": "1319dfd6-2fcb-4f5f-9e03-c039cbf31d21", 446 | "metadata": {}, 447 | "outputs": [ 448 | { 449 | "name": "stdout", 450 | "output_type": "stream", 451 | "text": [ 452 | "{1, 2, 3, 4, 5}\n", 453 | "{1, 2, 3, 4, 5}\n" 454 | ] 455 | } 456 | ], 457 | "source": [ 458 | "set1 = {1, 2, 3}\n", 459 | "set2 = {3, 4, 5}\n", 460 | "\n", 461 | "union_set = set1 | set2 # Using the '|' operator\n", 462 | "print(union_set) # Output: {1, 2, 3, 4, 5}\n", 463 | "\n", 464 | "# Alternatively, using union()\n", 465 | "union_set = set1.union(set2)\n", 466 | "print(union_set) # Output: {1, 2, 3, 4, 5}\n" 467 | ] 468 | }, 469 | { 470 | "cell_type": "markdown", 471 | "id": "de368a0b-3bec-4ab0-9823-2234bd973e98", 472 | "metadata": {}, 473 | "source": [ 474 | "#### 4. Set Intersection ( **&** or **intersection( )** ):\n", 475 | "##### The intersection of two sets returns only the elements that are present in both sets." 476 | ] 477 | }, 478 | { 479 | "cell_type": "code", 480 | "execution_count": 36, 481 | "id": "e74f87d4-e732-4cc1-9067-7bb3d2a992c1", 482 | "metadata": {}, 483 | "outputs": [ 484 | { 485 | "name": "stdout", 486 | "output_type": "stream", 487 | "text": [ 488 | "{2, 3}\n", 489 | "{2, 3}\n" 490 | ] 491 | } 492 | ], 493 | "source": [ 494 | "set1 = {1, 2, 3}\n", 495 | "set2 = {2, 3, 4}\n", 496 | "\n", 497 | "intersection_set = set1 & set2 # Using the '&' operator\n", 498 | "print(intersection_set) # Output: {2, 3}\n", 499 | "\n", 500 | "# Alternatively, using intersection()\n", 501 | "intersection_set = set1.intersection(set2)\n", 502 | "print(intersection_set) # Output: {2, 3}" 503 | ] 504 | }, 505 | { 506 | "cell_type": "markdown", 507 | "id": "878d7422-efa1-476e-8534-5ec369863fcb", 508 | "metadata": {}, 509 | "source": [ 510 | "#### 5. Set Difference ( **-** or **difference( )**):\n", 511 | "##### The difference of two sets returns the elements that are present in the first set but not in the second." 512 | ] 513 | }, 514 | { 515 | "cell_type": "code", 516 | "execution_count": 37, 517 | "id": "b0898c9b-8ac6-4a12-81ee-9f226ea5de6c", 518 | "metadata": {}, 519 | "outputs": [ 520 | { 521 | "name": "stdout", 522 | "output_type": "stream", 523 | "text": [ 524 | "{1, 2}\n", 525 | "{1, 2}\n" 526 | ] 527 | } 528 | ], 529 | "source": [ 530 | "set1 = {1, 2, 3, 4}\n", 531 | "set2 = {3, 4, 5}\n", 532 | "\n", 533 | "difference_set = set1 - set2 # Using the '-' operator\n", 534 | "print(difference_set) # Output: {1, 2}\n", 535 | "\n", 536 | "# Alternatively, using difference()\n", 537 | "difference_set = set1.difference(set2)\n", 538 | "print(difference_set) # Output: {1, 2}" 539 | ] 540 | }, 541 | { 542 | "cell_type": "markdown", 543 | "id": "e6b46861-c2f6-4f9d-b12d-6113f2f582e2", 544 | "metadata": {}, 545 | "source": [ 546 | "#### 6. Set Symmetric Difference ( **^** or **symmetric_difference( )**):\n", 547 | "##### The symmetric difference of two sets returns the elements that are in either of the sets, but not in both." 548 | ] 549 | }, 550 | { 551 | "cell_type": "code", 552 | "execution_count": 38, 553 | "id": "5ad9934c-2101-44c5-b494-55e1d1df1b8f", 554 | "metadata": {}, 555 | "outputs": [ 556 | { 557 | "name": "stdout", 558 | "output_type": "stream", 559 | "text": [ 560 | "{1, 2, 4, 5}\n", 561 | "{1, 2, 4, 5}\n" 562 | ] 563 | } 564 | ], 565 | "source": [ 566 | "set1 = {1, 2, 3}\n", 567 | "set2 = {3, 4, 5}\n", 568 | "\n", 569 | "symmetric_difference_set = set1 ^ set2 # Using the '^' operator\n", 570 | "print(symmetric_difference_set) # Output: {1, 2, 4, 5}\n", 571 | "\n", 572 | "# Alternatively, using symmetric_difference()\n", 573 | "symmetric_difference_set = set1.symmetric_difference(set2)\n", 574 | "print(symmetric_difference_set) # Output: {1, 2, 4, 5}\n" 575 | ] 576 | }, 577 | { 578 | "cell_type": "markdown", 579 | "id": "007a850a-fc62-4568-9752-63f5be1f151b", 580 | "metadata": {}, 581 | "source": [ 582 | "#### 7. Checking Membership in a Set:\n", 583 | "##### You can check if an element is present in a set using the **in** keyword." 584 | ] 585 | }, 586 | { 587 | "cell_type": "code", 588 | "execution_count": 39, 589 | "id": "2238ab2d-df5c-45d4-80c2-a45ac106f697", 590 | "metadata": {}, 591 | "outputs": [ 592 | { 593 | "name": "stdout", 594 | "output_type": "stream", 595 | "text": [ 596 | "True\n", 597 | "False\n" 598 | ] 599 | } 600 | ], 601 | "source": [ 602 | "my_set = {1, 2, 3, 4}\n", 603 | "print(2 in my_set) # Output: True\n", 604 | "print(5 in my_set) # Output: False" 605 | ] 606 | }, 607 | { 608 | "cell_type": "markdown", 609 | "id": "2e95e744-75be-4fd7-aa52-b7bc6d2297c6", 610 | "metadata": {}, 611 | "source": [ 612 | "#### 8. Set Size:\n", 613 | "##### You can find the number of elements in a set using the **len( )** function." 614 | ] 615 | }, 616 | { 617 | "cell_type": "code", 618 | "execution_count": 40, 619 | "id": "04486efc-f746-4d67-8be3-91fe5d736f0d", 620 | "metadata": {}, 621 | "outputs": [ 622 | { 623 | "name": "stdout", 624 | "output_type": "stream", 625 | "text": [ 626 | "4\n" 627 | ] 628 | } 629 | ], 630 | "source": [ 631 | "my_set = {1, 2, 3, 4}\n", 632 | "print(len(my_set)) # Output: 4" 633 | ] 634 | }, 635 | { 636 | "cell_type": "markdown", 637 | "id": "cc5af2b0-4eca-4fd5-b73b-dcf056fc83f5", 638 | "metadata": {}, 639 | "source": [ 640 | "#### 9. methods for relating two sets" 641 | ] 642 | }, 643 | { 644 | "cell_type": "code", 645 | "execution_count": 46, 646 | "id": "fe49eaba-8620-4565-b13b-9ce4c7da34a8", 647 | "metadata": {}, 648 | "outputs": [ 649 | { 650 | "name": "stdout", 651 | "output_type": "stream", 652 | "text": [ 653 | "False\n", 654 | "False\n", 655 | "False\n" 656 | ] 657 | } 658 | ], 659 | "source": [ 660 | "set1 = {1, 2, 3}\n", 661 | "set2 = {3, 4, 5}\n", 662 | "print(set1.issuperset(set2)) # Test whether every element in other is in the set.\n", 663 | "\n", 664 | "print(set1.issubset(set2)) # Test whether every element in the set is in other.\n", 665 | "\n", 666 | "print(set1.isdisjoint(set2)) # Return True if two sets have a null intersection." 667 | ] 668 | }, 669 | { 670 | "cell_type": "code", 671 | "execution_count": 44, 672 | "id": "e1783921-a631-4c2a-9506-a1411d88a59f", 673 | "metadata": { 674 | "scrolled": true 675 | }, 676 | "outputs": [ 677 | { 678 | "name": "stdout", 679 | "output_type": "stream", 680 | "text": [ 681 | "Help on class set in module builtins:\n", 682 | "\n", 683 | "class set(object)\n", 684 | " | set() -> new empty set object\n", 685 | " | set(iterable) -> new set object\n", 686 | " |\n", 687 | " | Build an unordered collection of unique elements.\n", 688 | " |\n", 689 | " | Methods defined here:\n", 690 | " |\n", 691 | " | __and__(self, value, /)\n", 692 | " | Return self&value.\n", 693 | " |\n", 694 | " | __contains__(...)\n", 695 | " | x.__contains__(y) <==> y in x.\n", 696 | " |\n", 697 | " | __eq__(self, value, /)\n", 698 | " | Return self==value.\n", 699 | " |\n", 700 | " | __ge__(self, value, /)\n", 701 | " | Return self>=value.\n", 702 | " |\n", 703 | " | __getattribute__(self, name, /)\n", 704 | " | Return getattr(self, name).\n", 705 | " |\n", 706 | " | __gt__(self, value, /)\n", 707 | " | Return self>value.\n", 708 | " |\n", 709 | " | __iand__(self, value, /)\n", 710 | " | Return self&=value.\n", 711 | " |\n", 712 | " | __init__(self, /, *args, **kwargs)\n", 713 | " | Initialize self. See help(type(self)) for accurate signature.\n", 714 | " |\n", 715 | " | __ior__(self, value, /)\n", 716 | " | Return self|=value.\n", 717 | " |\n", 718 | " | __isub__(self, value, /)\n", 719 | " | Return self-=value.\n", 720 | " |\n", 721 | " | __iter__(self, /)\n", 722 | " | Implement iter(self).\n", 723 | " |\n", 724 | " | __ixor__(self, value, /)\n", 725 | " | Return self^=value.\n", 726 | " |\n", 727 | " | __le__(self, value, /)\n", 728 | " | Return self<=value.\n", 729 | " |\n", 730 | " | __len__(self, /)\n", 731 | " | Return len(self).\n", 732 | " |\n", 733 | " | __lt__(self, value, /)\n", 734 | " | Return self size of S in memory, in bytes\n", 762 | " |\n", 763 | " | __sub__(self, value, /)\n", 764 | " | Return self-value.\n", 765 | " |\n", 766 | " | __xor__(self, value, /)\n", 767 | " | Return self^value.\n", 768 | " |\n", 769 | " | add(...)\n", 770 | " | Add an element to a set.\n", 771 | " |\n", 772 | " | This has no effect if the element is already present.\n", 773 | " |\n", 774 | " | clear(...)\n", 775 | " | Remove all elements from this set.\n", 776 | " |\n", 777 | " | copy(...)\n", 778 | " | Return a shallow copy of a set.\n", 779 | " |\n", 780 | " | difference(...)\n", 781 | " | Return the difference of two or more sets as a new set.\n", 782 | " |\n", 783 | " | (i.e. all elements that are in this set but not the others.)\n", 784 | " |\n", 785 | " | difference_update(...)\n", 786 | " | Remove all elements of another set from this set.\n", 787 | " |\n", 788 | " | discard(...)\n", 789 | " | Remove an element from a set if it is a member.\n", 790 | " |\n", 791 | " | Unlike set.remove(), the discard() method does not raise\n", 792 | " | an exception when an element is missing from the set.\n", 793 | " |\n", 794 | " | intersection(...)\n", 795 | " | Return the intersection of two sets as a new set.\n", 796 | " |\n", 797 | " | (i.e. all elements that are in both sets.)\n", 798 | " |\n", 799 | " | intersection_update(...)\n", 800 | " | Update a set with the intersection of itself and another.\n", 801 | " |\n", 802 | " | isdisjoint(...)\n", 803 | " | Return True if two sets have a null intersection.\n", 804 | " |\n", 805 | " | issubset(self, other, /)\n", 806 | " | Test whether every element in the set is in other.\n", 807 | " |\n", 808 | " | issuperset(self, other, /)\n", 809 | " | Test whether every element in other is in the set.\n", 810 | " |\n", 811 | " | pop(...)\n", 812 | " | Remove and return an arbitrary set element.\n", 813 | " | Raises KeyError if the set is empty.\n", 814 | " |\n", 815 | " | remove(...)\n", 816 | " | Remove an element from a set; it must be a member.\n", 817 | " |\n", 818 | " | If the element is not a member, raise a KeyError.\n", 819 | " |\n", 820 | " | symmetric_difference(...)\n", 821 | " | Return the symmetric difference of two sets as a new set.\n", 822 | " |\n", 823 | " | (i.e. all elements that are in exactly one of the sets.)\n", 824 | " |\n", 825 | " | symmetric_difference_update(...)\n", 826 | " | Update a set with the symmetric difference of itself and another.\n", 827 | " |\n", 828 | " | union(...)\n", 829 | " | Return the union of sets as a new set.\n", 830 | " |\n", 831 | " | (i.e. all elements that are in either set.)\n", 832 | " |\n", 833 | " | update(...)\n", 834 | " | Update a set with the union of itself and others.\n", 835 | " |\n", 836 | " | ----------------------------------------------------------------------\n", 837 | " | Class methods defined here:\n", 838 | " |\n", 839 | " | __class_getitem__(...)\n", 840 | " | See PEP 585\n", 841 | " |\n", 842 | " | ----------------------------------------------------------------------\n", 843 | " | Static methods defined here:\n", 844 | " |\n", 845 | " | __new__(*args, **kwargs)\n", 846 | " | Create and return a new object. See help(type) for accurate signature.\n", 847 | " |\n", 848 | " | ----------------------------------------------------------------------\n", 849 | " | Data and other attributes defined here:\n", 850 | " |\n", 851 | " | __hash__ = None\n", 852 | "\n" 853 | ] 854 | } 855 | ], 856 | "source": [ 857 | "help(set)" 858 | ] 859 | }, 860 | { 861 | "cell_type": "markdown", 862 | "id": "e963b013-2794-46dd-bb27-539409e15ccb", 863 | "metadata": {}, 864 | "source": [ 865 | "#### We know indexing & slicing won't work bcz set is an _ _ _ _ _ _ _ collection??\n", 866 | "#### What about our favourite concat + and rep * operators??" 867 | ] 868 | }, 869 | { 870 | "cell_type": "code", 871 | "execution_count": 47, 872 | "id": "d5d713bc-adaa-48a9-b5b0-ec918c316736", 873 | "metadata": {}, 874 | "outputs": [ 875 | { 876 | "ename": "TypeError", 877 | "evalue": "unsupported operand type(s) for +: 'set' and 'set'", 878 | "output_type": "error", 879 | "traceback": [ 880 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 881 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 882 | "Cell \u001b[1;32mIn[47], line 3\u001b[0m\n\u001b[0;32m 1\u001b[0m set1 \u001b[38;5;241m=\u001b[39m {\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m3\u001b[39m}\n\u001b[0;32m 2\u001b[0m set2 \u001b[38;5;241m=\u001b[39m {\u001b[38;5;241m3\u001b[39m, \u001b[38;5;241m4\u001b[39m, \u001b[38;5;241m5\u001b[39m}\n\u001b[1;32m----> 3\u001b[0m set3 \u001b[38;5;241m=\u001b[39m \u001b[43mset1\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m+\u001b[39;49m\u001b[43m \u001b[49m\u001b[43mset2\u001b[49m\n", 883 | "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'set' and 'set'" 884 | ] 885 | } 886 | ], 887 | "source": [ 888 | "set1 = {1, 2, 3}\n", 889 | "set2 = {3, 4, 5}\n", 890 | "set3 = set1 + set2" 891 | ] 892 | }, 893 | { 894 | "cell_type": "code", 895 | "execution_count": 48, 896 | "id": "13c78b15-c8ff-42fe-bdc0-f49e65851179", 897 | "metadata": {}, 898 | "outputs": [ 899 | { 900 | "ename": "TypeError", 901 | "evalue": "unsupported operand type(s) for *: 'set' and 'int'", 902 | "output_type": "error", 903 | "traceback": [ 904 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 905 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 906 | "Cell \u001b[1;32mIn[48], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m set1 \u001b[38;5;241m=\u001b[39m {\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m3\u001b[39m}\n\u001b[1;32m----> 2\u001b[0m rep \u001b[38;5;241m=\u001b[39m \u001b[43mset1\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m2\u001b[39;49m\n", 907 | "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for *: 'set' and 'int'" 908 | ] 909 | } 910 | ], 911 | "source": [ 912 | "set1 = {1, 2, 3}\n", 913 | "rep = set1*2" 914 | ] 915 | }, 916 | { 917 | "attachments": {}, 918 | "cell_type": "markdown", 919 | "id": "0e95c389-0b43-4af5-af53-d993ae82493b", 920 | "metadata": {}, 921 | "source": [ 922 | "### NESTED SETS\n", 923 | "#### We cannot include a set as a member of another set\n" 924 | ] 925 | }, 926 | { 927 | "cell_type": "code", 928 | "execution_count": 53, 929 | "id": "13d077d3-9542-44e3-8c05-0504ebcbef5d", 930 | "metadata": {}, 931 | "outputs": [ 932 | { 933 | "ename": "TypeError", 934 | "evalue": "unhashable type: 'set'", 935 | "output_type": "error", 936 | "traceback": [ 937 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 938 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 939 | "Cell \u001b[1;32mIn[53], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m nested_set \u001b[38;5;241m=\u001b[39m {{\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m}, {\u001b[38;5;241m3\u001b[39m, \u001b[38;5;241m4\u001b[39m}, {\u001b[38;5;241m5\u001b[39m, \u001b[38;5;241m6\u001b[39m}}\n\u001b[0;32m 2\u001b[0m \u001b[38;5;28mprint\u001b[39m(nested_set)\n", 940 | "\u001b[1;31mTypeError\u001b[0m: unhashable type: 'set'" 941 | ] 942 | } 943 | ], 944 | "source": [ 945 | "nested_set = {{1, 2}, {3, 4}, {5, 6}}\n", 946 | "print(nested_set)" 947 | ] 948 | }, 949 | { 950 | "cell_type": "markdown", 951 | "id": "d3ef5216-d842-4fca-a68f-6f6e1546be23", 952 | "metadata": {}, 953 | "source": [ 954 | "### SET COMPREHENSION" 955 | ] 956 | }, 957 | { 958 | "cell_type": "markdown", 959 | "id": "8d085def-365e-4164-9469-4a0315ca1bc8", 960 | "metadata": {}, 961 | "source": [ 962 | "##### Similar to that of list comprehension but has to comply with the validity of sets\n", 963 | "* Case 1: Single for loop" 964 | ] 965 | }, 966 | { 967 | "cell_type": "code", 968 | "execution_count": 56, 969 | "id": "966e783b-34f8-4332-91f1-5e81da765d6b", 970 | "metadata": {}, 971 | "outputs": [ 972 | { 973 | "data": { 974 | "text/plain": [ 975 | "{2, 3, 4, 5, 6, 7, 8, 9, 10}" 976 | ] 977 | }, 978 | "execution_count": 56, 979 | "metadata": {}, 980 | "output_type": "execute_result" 981 | } 982 | ], 983 | "source": [ 984 | "{n+1 for n in range(1,10)}" 985 | ] 986 | }, 987 | { 988 | "cell_type": "code", 989 | "execution_count": 57, 990 | "id": "2930125f-2da4-4d2a-b7de-fb208dadd138", 991 | "metadata": {}, 992 | "outputs": [ 993 | { 994 | "data": { 995 | "text/plain": [ 996 | "{(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)}" 997 | ] 998 | }, 999 | "execution_count": 57, 1000 | "metadata": {}, 1001 | "output_type": "execute_result" 1002 | } 1003 | ], 1004 | "source": [ 1005 | "{(n,n*n) for n in range(1,10)}" 1006 | ] 1007 | }, 1008 | { 1009 | "cell_type": "markdown", 1010 | "id": "b66e5b7e-c02d-403e-bfa0-896848377886", 1011 | "metadata": {}, 1012 | "source": [ 1013 | "* Case 2: for loop with if\n", 1014 | "- This will help to generate a set for a given range when the condition given in if is True\n", 1015 | "- Example – generate a set of numbers that are divisible by 6 within the range of 0 to 100\n", 1016 | "\n" 1017 | ] 1018 | }, 1019 | { 1020 | "cell_type": "code", 1021 | "execution_count": 60, 1022 | "id": "04adf7f5-d4d2-476d-b045-2b4f9eaf88a4", 1023 | "metadata": {}, 1024 | "outputs": [ 1025 | { 1026 | "data": { 1027 | "text/plain": [ 1028 | "{0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96}" 1029 | ] 1030 | }, 1031 | "execution_count": 60, 1032 | "metadata": {}, 1033 | "output_type": "execute_result" 1034 | } 1035 | ], 1036 | "source": [ 1037 | "{n for n in range(0,100) if n%6==0}" 1038 | ] 1039 | }, 1040 | { 1041 | "cell_type": "markdown", 1042 | "id": "4d2f7f5e-06ef-496d-9f0d-b8cea443db12", 1043 | "metadata": {}, 1044 | "source": [ 1045 | "* Case 3: for with if and else\n", 1046 | " - In this case, if clause and else will be written before for loop\n", 1047 | " - To generate n\\*n if n>5 and n\\*n\\*n if n<=5" 1048 | ] 1049 | }, 1050 | { 1051 | "cell_type": "code", 1052 | "execution_count": 61, 1053 | "id": "d77fe76c-af76-41fc-a2df-9ba2b4c735f5", 1054 | "metadata": {}, 1055 | "outputs": [ 1056 | { 1057 | "name": "stdout", 1058 | "output_type": "stream", 1059 | "text": [ 1060 | "{-512, 0, 1, -125, 8, -1000, 27, 36, -729, -216, -343, 49, -64, 64, 81, -27, -8, 125, -1}\n" 1061 | ] 1062 | } 1063 | ], 1064 | "source": [ 1065 | "S = {n*n if n>5 else n*n*n for n in range(-10,10)}\n", 1066 | "print(S)" 1067 | ] 1068 | }, 1069 | { 1070 | "cell_type": "code", 1071 | "execution_count": 64, 1072 | "id": "44a84cf2-8b08-40b6-b2e8-ae967fd1e829", 1073 | "metadata": {}, 1074 | "outputs": [ 1075 | { 1076 | "data": { 1077 | "text/plain": [ 1078 | "{0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 3, 4}" 1079 | ] 1080 | }, 1081 | "execution_count": 64, 1082 | "metadata": {}, 1083 | "output_type": "execute_result" 1084 | } 1085 | ], 1086 | "source": [ 1087 | "#The condition should not lead to duplication of elements\n", 1088 | "{n**0.5 if n<6 else n//4 for n in range(0,20)}" 1089 | ] 1090 | }, 1091 | { 1092 | "cell_type": "markdown", 1093 | "id": "4f3bb5d6-cc12-4fae-bae7-7c054996378a", 1094 | "metadata": {}, 1095 | "source": [ 1096 | "### Example: Practical Use of Sets\n", 1097 | " #### Suppose you have two lists of students who attended two different events. You want to find:\n", 1098 | "\n", 1099 | "* All the unique students who attended at least one event.\n", 1100 | "* The students who attended both events.\n", 1101 | "* The students who attended only one of the events." 1102 | ] 1103 | }, 1104 | { 1105 | "cell_type": "code", 1106 | "execution_count": 55, 1107 | "id": "c094b927-cde6-499c-9b1c-f64a611cd675", 1108 | "metadata": {}, 1109 | "outputs": [ 1110 | { 1111 | "name": "stdout", 1112 | "output_type": "stream", 1113 | "text": [ 1114 | "All attendees: {'Vikas', 'Chaitanya', 'Anubhav', 'Udisha', 'Abhrajit', 'Sagar'}\n", 1115 | "Common attendees: {'Vikas', 'Chaitanya'}\n", 1116 | "Unique attendees: {'Anubhav', 'Udisha', 'Abhrajit', 'Sagar'}\n" 1117 | ] 1118 | } 1119 | ], 1120 | "source": [ 1121 | "event1_attendees = {\"Chaitanya\", \"Abhrajit\", \"Vikas\", \"Anubhav\"}\n", 1122 | "event2_attendees = {\"Sagar\", \"Vikas\", \"Chaitanya\", \"Udisha\"}\n", 1123 | "\n", 1124 | "# All unique attendees\n", 1125 | "all_attendees = event1_attendees | event2_attendees # Union\n", 1126 | "print(\"All attendees:\", all_attendees) \n", 1127 | "\n", 1128 | "# Students who attended both events\n", 1129 | "common_attendees = event1_attendees & event2_attendees # Intersection\n", 1130 | "print(\"Common attendees:\", common_attendees) \n", 1131 | "\n", 1132 | "# Students who attended only one event\n", 1133 | "unique_attendees = event1_attendees ^ event2_attendees # Symmetric difference\n", 1134 | "print(\"Unique attendees:\", unique_attendees) \n" 1135 | ] 1136 | }, 1137 | { 1138 | "cell_type": "code", 1139 | "execution_count": 26, 1140 | "id": "2237ed83-77c4-4dbc-980c-cf2a3fbd7e39", 1141 | "metadata": {}, 1142 | "outputs": [ 1143 | { 1144 | "name": "stdout", 1145 | "output_type": "stream", 1146 | "text": [ 1147 | "(('pankaj', 73), ('rahul', 56), ('abhinav', 84), ('devansh', 47), ('amrit', 66))\n", 1148 | "[('devansh', 47), ('rahul', 56), ('amrit', 66), ('pankaj', 73), ('abhinav', 84)]\n", 1149 | "('devansh', 47)\n", 1150 | "('abhinav', 84)\n", 1151 | "devansh\n", 1152 | "47\n", 1153 | "('pankaj', 73)\n", 1154 | "pankaj\n" 1155 | ] 1156 | } 1157 | ], 1158 | "source": [ 1159 | "\n", 1160 | "students =(\"pankaj\",\"rahul\",\"abhinav\",\"devansh\",\"amrit\")\n", 1161 | "marks = (73,56,84,47,66)\n", 1162 | "d = tuple(zip(students,marks))\n", 1163 | "print(d)\n", 1164 | "l=list(d)\n", 1165 | "l.sort(key=lambda x:x[1])\n", 1166 | "print(l)\n", 1167 | "print(l[0])\n", 1168 | "print(l[4])\n", 1169 | "print(l[0][0])\n", 1170 | "print(l[0][1])\n", 1171 | "print(l[3])\n", 1172 | "print(l[3][0])" 1173 | ] 1174 | }, 1175 | { 1176 | "cell_type": "code", 1177 | "execution_count": 31, 1178 | "id": "a8f45708-71e4-4e8a-a98e-a1c263635f0e", 1179 | "metadata": {}, 1180 | "outputs": [ 1181 | { 1182 | "name": "stdout", 1183 | "output_type": "stream", 1184 | "text": [ 1185 | "[(47, 'devansh'), (56, 'rahul'), (66, 'amrit'), (73, 'pankaj'), (84, 'abhinav')]\n", 1186 | "[('devansh', 47), ('rahul', 56), ('amrit', 66), ('pankaj', 73), ('abhinav', 84)]\n" 1187 | ] 1188 | } 1189 | ], 1190 | "source": [ 1191 | "students =(\"pankaj\",\"rahul\",\"abhinav\",\"devansh\",\"amrit\")\n", 1192 | "marks = (73,56,84,47,66)\n", 1193 | "\n", 1194 | "comb = tuple(zip(marks, students))\n", 1195 | "nc = sorted(comb)\n", 1196 | "print(nc)\n", 1197 | "nl = [tuple(reversed(i)) for i in nc]\n", 1198 | "print(nl)" 1199 | ] 1200 | }, 1201 | { 1202 | "cell_type": "markdown", 1203 | "id": "2c07715c-65b6-4a2b-b50a-033c3c379720", 1204 | "metadata": {}, 1205 | "source": [ 1206 | "##### expected output\n", 1207 | "Combined Tuple: (('Bibek', 67), ('Pahul', 82), ('Yugraj', 91), ('Sonny', 55), ('Parnab', 78)) \n", 1208 | "Sorted by Marks (Ascending): [('Sonny', 55), ('Bibek', 67), ('Parnab', 78), ('Pahul', 82), ('Yugraj', 91)] \n", 1209 | "Student with Lowest Marks: Sonny, Marks: 55 \n", 1210 | "Student with Highest Marks: Yugraj, Marks: 91 \n", 1211 | "Student with Second-Highest Marks: Pahul, Marks: 82 \n", 1212 | "Number of students scoring above 75: 3" 1213 | ] 1214 | }, 1215 | { 1216 | "cell_type": "code", 1217 | "execution_count": 32, 1218 | "id": "90883c49-62c6-403d-ae4e-4d2b1db38841", 1219 | "metadata": {}, 1220 | "outputs": [ 1221 | { 1222 | "name": "stdout", 1223 | "output_type": "stream", 1224 | "text": [ 1225 | "1\n" 1226 | ] 1227 | } 1228 | ], 1229 | "source": [ 1230 | "print(len([i for i in nl if i[1]>75]))\n" 1231 | ] 1232 | }, 1233 | { 1234 | "cell_type": "code", 1235 | "execution_count": null, 1236 | "id": "c88e4905-5ef1-4407-89da-7bccfb48d50d", 1237 | "metadata": {}, 1238 | "outputs": [], 1239 | "source": [] 1240 | } 1241 | ], 1242 | "metadata": { 1243 | "kernelspec": { 1244 | "display_name": "Python 3 (ipykernel)", 1245 | "language": "python", 1246 | "name": "python3" 1247 | }, 1248 | "language_info": { 1249 | "codemirror_mode": { 1250 | "name": "ipython", 1251 | "version": 3 1252 | }, 1253 | "file_extension": ".py", 1254 | "mimetype": "text/x-python", 1255 | "name": "python", 1256 | "nbconvert_exporter": "python", 1257 | "pygments_lexer": "ipython3", 1258 | "version": "3.12.6" 1259 | } 1260 | }, 1261 | "nbformat": 4, 1262 | "nbformat_minor": 5 1263 | } 1264 | -------------------------------------------------------------------------------- /Numpy_ArrayDtypes_from_ManjuMam.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 8, 6 | "id": "da6e09b6-8c65-4b77-b417-4721faded1f4", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "import numpy as np" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "b0b9f329-f721-4a36-b49b-9cd994249709", 16 | "metadata": {}, 17 | "source": [ 18 | "This command will import numpy package into the local symbol table with a dummy name 'np'" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 9, 24 | "id": "6f2e4a89-f94d-4ac4-bfca-70cce852be19", 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "L=[1,2,3,4,5] # intializing a list" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 10, 34 | "id": "923b385f-3363-463f-8996-91195360b599", 35 | "metadata": {}, 36 | "outputs": [ 37 | { 38 | "data": { 39 | "text/plain": [ 40 | "array([1, 2, 3, 4, 5])" 41 | ] 42 | }, 43 | "execution_count": 10, 44 | "metadata": {}, 45 | "output_type": "execute_result" 46 | } 47 | ], 48 | "source": [ 49 | "np.array(L)" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 11, 55 | "id": "f1e2ba83-35b9-48fc-8b78-8644a9482558", 56 | "metadata": {}, 57 | "outputs": [ 58 | { 59 | "name": "stdout", 60 | "output_type": "stream", 61 | "text": [ 62 | "Help on built-in function array in module numpy:\n", 63 | "\n", 64 | "array(...)\n", 65 | " array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,\n", 66 | " like=None)\n", 67 | " \n", 68 | " Create an array.\n", 69 | " \n", 70 | " Parameters\n", 71 | " ----------\n", 72 | " object : array_like\n", 73 | " An array, any object exposing the array interface, an object whose\n", 74 | " ``__array__`` method returns an array, or any (nested) sequence.\n", 75 | " If object is a scalar, a 0-dimensional array containing object is\n", 76 | " returned.\n", 77 | " dtype : data-type, optional\n", 78 | " The desired data-type for the array. If not given, NumPy will try to use\n", 79 | " a default ``dtype`` that can represent the values (by applying promotion\n", 80 | " rules when necessary.)\n", 81 | " copy : bool, optional\n", 82 | " If true (default), then the object is copied. Otherwise, a copy will\n", 83 | " only be made if ``__array__`` returns a copy, if obj is a nested\n", 84 | " sequence, or if a copy is needed to satisfy any of the other\n", 85 | " requirements (``dtype``, ``order``, etc.).\n", 86 | " order : {'K', 'A', 'C', 'F'}, optional\n", 87 | " Specify the memory layout of the array. If object is not an array, the\n", 88 | " newly created array will be in C order (row major) unless 'F' is\n", 89 | " specified, in which case it will be in Fortran order (column major).\n", 90 | " If object is an array the following holds.\n", 91 | " \n", 92 | " ===== ========= ===================================================\n", 93 | " order no copy copy=True\n", 94 | " ===== ========= ===================================================\n", 95 | " 'K' unchanged F & C order preserved, otherwise most similar order\n", 96 | " 'A' unchanged F order if input is F and not C, otherwise C order\n", 97 | " 'C' C order C order\n", 98 | " 'F' F order F order\n", 99 | " ===== ========= ===================================================\n", 100 | " \n", 101 | " When ``copy=False`` and a copy is made for other reasons, the result is\n", 102 | " the same as if ``copy=True``, with some exceptions for 'A', see the\n", 103 | " Notes section. The default order is 'K'.\n", 104 | " subok : bool, optional\n", 105 | " If True, then sub-classes will be passed-through, otherwise\n", 106 | " the returned array will be forced to be a base-class array (default).\n", 107 | " ndmin : int, optional\n", 108 | " Specifies the minimum number of dimensions that the resulting\n", 109 | " array should have. Ones will be prepended to the shape as\n", 110 | " needed to meet this requirement.\n", 111 | " like : array_like, optional\n", 112 | " Reference object to allow the creation of arrays which are not\n", 113 | " NumPy arrays. If an array-like passed in as ``like`` supports\n", 114 | " the ``__array_function__`` protocol, the result will be defined\n", 115 | " by it. In this case, it ensures the creation of an array object\n", 116 | " compatible with that passed in via this argument.\n", 117 | " \n", 118 | " .. versionadded:: 1.20.0\n", 119 | " \n", 120 | " Returns\n", 121 | " -------\n", 122 | " out : ndarray\n", 123 | " An array object satisfying the specified requirements.\n", 124 | " \n", 125 | " See Also\n", 126 | " --------\n", 127 | " empty_like : Return an empty array with shape and type of input.\n", 128 | " ones_like : Return an array of ones with shape and type of input.\n", 129 | " zeros_like : Return an array of zeros with shape and type of input.\n", 130 | " full_like : Return a new array with shape of input filled with value.\n", 131 | " empty : Return a new uninitialized array.\n", 132 | " ones : Return a new array setting values to one.\n", 133 | " zeros : Return a new array setting values to zero.\n", 134 | " full : Return a new array of given shape filled with value.\n", 135 | " \n", 136 | " \n", 137 | " Notes\n", 138 | " -----\n", 139 | " When order is 'A' and ``object`` is an array in neither 'C' nor 'F' order,\n", 140 | " and a copy is forced by a change in dtype, then the order of the result is\n", 141 | " not necessarily 'C' as expected. This is likely a bug.\n", 142 | " \n", 143 | " Examples\n", 144 | " --------\n", 145 | " >>> np.array([1, 2, 3])\n", 146 | " array([1, 2, 3])\n", 147 | " \n", 148 | " Upcasting:\n", 149 | " \n", 150 | " >>> np.array([1, 2, 3.0])\n", 151 | " array([ 1., 2., 3.])\n", 152 | " \n", 153 | " More than one dimension:\n", 154 | " \n", 155 | " >>> np.array([[1, 2], [3, 4]])\n", 156 | " array([[1, 2],\n", 157 | " [3, 4]])\n", 158 | " \n", 159 | " Minimum dimensions 2:\n", 160 | " \n", 161 | " >>> np.array([1, 2, 3], ndmin=2)\n", 162 | " array([[1, 2, 3]])\n", 163 | " \n", 164 | " Type provided:\n", 165 | " \n", 166 | " >>> np.array([1, 2, 3], dtype=complex)\n", 167 | " array([ 1.+0.j, 2.+0.j, 3.+0.j])\n", 168 | " \n", 169 | " Data-type consisting of more than one element:\n", 170 | " \n", 171 | " >>> x = np.array([(1,2),(3,4)],dtype=[('a','>> x['a']\n", 173 | " array([1, 3])\n", 174 | " \n", 175 | " Creating an array from sub-classes:\n", 176 | " \n", 177 | " >>> np.array(np.mat('1 2; 3 4'))\n", 178 | " array([[1, 2],\n", 179 | " [3, 4]])\n", 180 | " \n", 181 | " >>> np.array(np.mat('1 2; 3 4'), subok=True)\n", 182 | " matrix([[1, 2],\n", 183 | " [3, 4]])\n", 184 | "\n" 185 | ] 186 | } 187 | ], 188 | "source": [ 189 | "help(np.array)" 190 | ] 191 | }, 192 | { 193 | "cell_type": "markdown", 194 | "id": "6d3c96fe-64b3-4ba0-80d7-ffedac9c5e4c", 195 | "metadata": {}, 196 | "source": [ 197 | "array() is one of the most important methods that is being used for contructing arrays. It can convert a list or a tuple into a valid usable array. A set will be converted into array but it will not construct a usable array with customized datatype. This can be illustrated in the following lines." 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": 12, 203 | "id": "a5b3166c-b0b5-46f7-b910-bfb0aafa10fd", 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "T=1,2,3,4 # tuple" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": 13, 213 | "id": "facc131c-cd92-4117-aebd-ef8928cb2731", 214 | "metadata": {}, 215 | "outputs": [], 216 | "source": [ 217 | "A=np.array(T) # converting tuple into array" 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": 14, 223 | "id": "610922f7-8b39-461b-99d4-7ca86aa80e40", 224 | "metadata": {}, 225 | "outputs": [ 226 | { 227 | "data": { 228 | "text/plain": [ 229 | "array([1, 2, 3, 4])" 230 | ] 231 | }, 232 | "execution_count": 14, 233 | "metadata": {}, 234 | "output_type": "execute_result" 235 | } 236 | ], 237 | "source": [ 238 | "A" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": 15, 244 | "id": "8fc649b9-f086-4e00-a787-6e9b5f967419", 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "S={1,2,3,4} # set " 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": 16, 254 | "id": "c8dc7b9f-7327-403c-8244-fe899c1201e8", 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "B=np.array(S) # converting set into an array" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": 17, 264 | "id": "160035e6-3873-4045-a2e1-a083fb9eee18", 265 | "metadata": {}, 266 | "outputs": [ 267 | { 268 | "data": { 269 | "text/plain": [ 270 | "array({1, 2, 3, 4}, dtype=object)" 271 | ] 272 | }, 273 | "execution_count": 17, 274 | "metadata": {}, 275 | "output_type": "execute_result" 276 | } 277 | ], 278 | "source": [ 279 | "B" 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "id": "b653f00c-f361-4277-96b9-f88d90c5243a", 285 | "metadata": {}, 286 | "source": [ 287 | "Here we can see that datatype of the invidual elements of the set is integer but dtype of the array is taken as 'object' by the interpreter. ( It implies that the whole set is taken as a single element of the array)" 288 | ] 289 | }, 290 | { 291 | "cell_type": "code", 292 | "execution_count": 18, 293 | "id": "4b203751-54a2-4ce7-9621-efd63d684b31", 294 | "metadata": {}, 295 | "outputs": [ 296 | { 297 | "name": "stdout", 298 | "output_type": "stream", 299 | "text": [ 300 | "\n" 301 | ] 302 | } 303 | ], 304 | "source": [ 305 | "print(type(B)) # to check the type of the variable B" 306 | ] 307 | }, 308 | { 309 | "cell_type": "markdown", 310 | "id": "2526097f-6644-4f5c-b9e8-8567ce96bf9c", 311 | "metadata": {}, 312 | "source": [ 313 | "The function constructed a valid 'n dimensional' (nd) array" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": 19, 319 | "id": "644a829c-16e6-44fb-b629-c542ce625dab", 320 | "metadata": {}, 321 | "outputs": [ 322 | { 323 | "data": { 324 | "text/plain": [ 325 | "dtype('int32')" 326 | ] 327 | }, 328 | "execution_count": 19, 329 | "metadata": {}, 330 | "output_type": "execute_result" 331 | } 332 | ], 333 | "source": [ 334 | "A.dtype # method dtype helps to identify the datatype of array elements" 335 | ] 336 | }, 337 | { 338 | "cell_type": "markdown", 339 | "id": "5a1ed871-d76b-4f5e-86ac-6c2ca4ec3833", 340 | "metadata": {}, 341 | "source": [ 342 | "'int32' indicates the datatype of each array element is integer and it occupies 4 bytes of memory location" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": 20, 348 | "id": "a119926d-512e-44cd-bab9-a63b219e6cc1", 349 | "metadata": {}, 350 | "outputs": [ 351 | { 352 | "data": { 353 | "text/plain": [ 354 | "dtype('O')" 355 | ] 356 | }, 357 | "execution_count": 20, 358 | "metadata": {}, 359 | "output_type": "execute_result" 360 | } 361 | ], 362 | "source": [ 363 | "B.dtype" 364 | ] 365 | }, 366 | { 367 | "cell_type": "markdown", 368 | "id": "eb616152-58ae-4257-af5b-04dc017e948a", 369 | "metadata": {}, 370 | "source": [ 371 | "Here dtype is 'O' means individual elements of the set can't be accessed " 372 | ] 373 | }, 374 | { 375 | "cell_type": "code", 376 | "execution_count": 21, 377 | "id": "effb3666-4d8d-47b4-9780-ac3d1574b331", 378 | "metadata": {}, 379 | "outputs": [], 380 | "source": [ 381 | "L=[1,2,3,[4,5,6],7,8,9]" 382 | ] 383 | }, 384 | { 385 | "cell_type": "code", 386 | "execution_count": 22, 387 | "id": "3278e6ed-740c-4a90-995a-d51962722cf2", 388 | "metadata": {}, 389 | "outputs": [ 390 | { 391 | "ename": "ValueError", 392 | "evalue": "setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (7,) + inhomogeneous part.", 393 | "output_type": "error", 394 | "traceback": [ 395 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 396 | "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", 397 | "Cell \u001b[1;32mIn[22], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m A\u001b[38;5;241m=\u001b[39m\u001b[43mnp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43marray\u001b[49m\u001b[43m(\u001b[49m\u001b[43mL\u001b[49m\u001b[43m)\u001b[49m\n", 398 | "\u001b[1;31mValueError\u001b[0m: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (7,) + inhomogeneous part." 399 | ] 400 | } 401 | ], 402 | "source": [ 403 | "A=np.array(L)" 404 | ] 405 | }, 406 | { 407 | "cell_type": "markdown", 408 | "id": "b09f9290-63d5-420a-9585-1d613a2e3968", 409 | "metadata": {}, 410 | "source": [ 411 | "To convert a list or tuple into a valid array, they shall be homogeneous in nature. In the above example, L is a nested list with one of its member is another list. numpy function 'array' can't convert this list into a valid array. Either all elements shall be integers or all elements shall be lists" 412 | ] 413 | }, 414 | { 415 | "cell_type": "code", 416 | "execution_count": 23, 417 | "id": "9d60d2c5-9d36-4edf-a640-fa16f41fb6b9", 418 | "metadata": {}, 419 | "outputs": [], 420 | "source": [ 421 | "L=[[1,2,3],[4,5,6]] # all elements are lists" 422 | ] 423 | }, 424 | { 425 | "cell_type": "code", 426 | "execution_count": 24, 427 | "id": "d1d77fc1-baaf-4bce-855d-732088534572", 428 | "metadata": {}, 429 | "outputs": [], 430 | "source": [ 431 | "A=np.array(L)" 432 | ] 433 | }, 434 | { 435 | "cell_type": "code", 436 | "execution_count": 25, 437 | "id": "9049ed39-32bb-43ae-9b1a-13c820169dbf", 438 | "metadata": {}, 439 | "outputs": [ 440 | { 441 | "data": { 442 | "text/plain": [ 443 | "array([[1, 2, 3],\n", 444 | " [4, 5, 6]])" 445 | ] 446 | }, 447 | "execution_count": 25, 448 | "metadata": {}, 449 | "output_type": "execute_result" 450 | } 451 | ], 452 | "source": [ 453 | "A" 454 | ] 455 | }, 456 | { 457 | "cell_type": "markdown", 458 | "id": "ca99bb75-0733-43c3-9d51-c3dad03c45d1", 459 | "metadata": {}, 460 | "source": [ 461 | "There are many built in methods that helps to analyze various features of an array. Some basic methods are\n", 462 | " 1. dtype- to identify the datatype of the array elements.\n", 463 | " dtype is also a keyword argument of array function that helps to customize the datatype of array elements.\n", 464 | "\n", 465 | " For example , A.dtype will return the datatype of array elements if A is an array\n", 466 | " But np.array(L, dtype='f4') will construct an array where each element is of single precisionfloating point format\n", 467 | "\n", 468 | "2. ndim - to identify the number of dimensions of the array\n", 469 | "3. size - to identify the total number of elements present in an array\n", 470 | "4. shape - In the case of a 2D array, this method returns the rows and columns\n" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": 26, 476 | "id": "d5e72c67-fc8b-45a6-bacd-dfc469dc5182", 477 | "metadata": {}, 478 | "outputs": [ 479 | { 480 | "data": { 481 | "text/plain": [ 482 | "dtype('int32')" 483 | ] 484 | }, 485 | "execution_count": 26, 486 | "metadata": {}, 487 | "output_type": "execute_result" 488 | } 489 | ], 490 | "source": [ 491 | "A.dtype" 492 | ] 493 | }, 494 | { 495 | "cell_type": "code", 496 | "execution_count": 27, 497 | "id": "e1b1e8e0-177c-42e4-96b8-4a154933c082", 498 | "metadata": {}, 499 | "outputs": [ 500 | { 501 | "data": { 502 | "text/plain": [ 503 | "2" 504 | ] 505 | }, 506 | "execution_count": 27, 507 | "metadata": {}, 508 | "output_type": "execute_result" 509 | } 510 | ], 511 | "source": [ 512 | "A.ndim # to check the number of dimensions, n=1 means a row array or column array, n=2 implies two dimensional array (eqvt to matrix)\n" 513 | ] 514 | }, 515 | { 516 | "cell_type": "code", 517 | "execution_count": 28, 518 | "id": "18016fd5-3799-4106-8118-8fa55da05b3e", 519 | "metadata": {}, 520 | "outputs": [ 521 | { 522 | "data": { 523 | "text/plain": [ 524 | "6" 525 | ] 526 | }, 527 | "execution_count": 28, 528 | "metadata": {}, 529 | "output_type": "execute_result" 530 | } 531 | ], 532 | "source": [ 533 | "A.size" 534 | ] 535 | }, 536 | { 537 | "cell_type": "code", 538 | "execution_count": 29, 539 | "id": "6ca26794-afc1-4352-8b20-546931f3748a", 540 | "metadata": {}, 541 | "outputs": [], 542 | "source": [ 543 | "B=np.array(L, dtype='f') # assigning floating point datatype" 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": 30, 549 | "id": "435b307f-c661-4859-a1f9-2824ceb34b33", 550 | "metadata": {}, 551 | "outputs": [ 552 | { 553 | "data": { 554 | "text/plain": [ 555 | "array([[1., 2., 3.],\n", 556 | " [4., 5., 6.]], dtype=float32)" 557 | ] 558 | }, 559 | "execution_count": 30, 560 | "metadata": {}, 561 | "output_type": "execute_result" 562 | } 563 | ], 564 | "source": [ 565 | "B" 566 | ] 567 | }, 568 | { 569 | "cell_type": "markdown", 570 | "id": "c3c6f1a6-0628-41b2-baf0-f2e7954e5ce5", 571 | "metadata": {}, 572 | "source": [ 573 | "'f' by deafult assigns single precision\n", 574 | "'f2' gives 16 bit floating point data\n", 575 | "'f4' single precision\n", 576 | "'f8' double precision" 577 | ] 578 | }, 579 | { 580 | "cell_type": "code", 581 | "execution_count": 31, 582 | "id": "7a191015-e60d-434e-9b19-da9e31afc695", 583 | "metadata": {}, 584 | "outputs": [], 585 | "source": [ 586 | "C=np.array(L,dtype='u4') # unsigned integer datatype" 587 | ] 588 | }, 589 | { 590 | "cell_type": "code", 591 | "execution_count": 32, 592 | "id": "85d1ebb0-3d9d-4999-a88b-cd02f975dd64", 593 | "metadata": {}, 594 | "outputs": [ 595 | { 596 | "data": { 597 | "text/plain": [ 598 | "array([[1, 2, 3],\n", 599 | " [4, 5, 6]], dtype=uint32)" 600 | ] 601 | }, 602 | "execution_count": 32, 603 | "metadata": {}, 604 | "output_type": "execute_result" 605 | } 606 | ], 607 | "source": [ 608 | "C" 609 | ] 610 | }, 611 | { 612 | "cell_type": "code", 613 | "execution_count": 33, 614 | "id": "6847f294-9da2-4e46-82be-27a06c709cf6", 615 | "metadata": {}, 616 | "outputs": [ 617 | { 618 | "ename": "TypeError", 619 | "evalue": "data type 'u' not understood", 620 | "output_type": "error", 621 | "traceback": [ 622 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 623 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 624 | "Cell \u001b[1;32mIn[33], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m D\u001b[38;5;241m=\u001b[39m\u001b[43mnp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43marray\u001b[49m\u001b[43m(\u001b[49m\u001b[43mL\u001b[49m\u001b[43m,\u001b[49m\u001b[43mdtype\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mu\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n", 625 | "\u001b[1;31mTypeError\u001b[0m: data type 'u' not understood" 626 | ] 627 | } 628 | ], 629 | "source": [ 630 | "D=np.array(L,dtype='u')" 631 | ] 632 | }, 633 | { 634 | "cell_type": "code", 635 | "execution_count": 34, 636 | "id": "0c56eab6-d5c2-4b00-85ac-b74ed8b0af08", 637 | "metadata": {}, 638 | "outputs": [], 639 | "source": [ 640 | "D=np.array(L,dtype='u2')" 641 | ] 642 | }, 643 | { 644 | "cell_type": "code", 645 | "execution_count": 35, 646 | "id": "e9847eed-ecb5-491d-a3ff-3be9c3e98792", 647 | "metadata": {}, 648 | "outputs": [ 649 | { 650 | "data": { 651 | "text/plain": [ 652 | "array([[1, 2, 3],\n", 653 | " [4, 5, 6]], dtype=uint16)" 654 | ] 655 | }, 656 | "execution_count": 35, 657 | "metadata": {}, 658 | "output_type": "execute_result" 659 | } 660 | ], 661 | "source": [ 662 | "D" 663 | ] 664 | }, 665 | { 666 | "cell_type": "code", 667 | "execution_count": 36, 668 | "id": "7325eb4d-5771-4ca3-bbc1-7528df2fac35", 669 | "metadata": {}, 670 | "outputs": [], 671 | "source": [ 672 | "E=np.array(L,dtype='complex')" 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": 37, 678 | "id": "52069dc5-3586-452c-893f-b72b99f60cb6", 679 | "metadata": {}, 680 | "outputs": [ 681 | { 682 | "data": { 683 | "text/plain": [ 684 | "array([[1.+0.j, 2.+0.j, 3.+0.j],\n", 685 | " [4.+0.j, 5.+0.j, 6.+0.j]])" 686 | ] 687 | }, 688 | "execution_count": 37, 689 | "metadata": {}, 690 | "output_type": "execute_result" 691 | } 692 | ], 693 | "source": [ 694 | "E" 695 | ] 696 | }, 697 | { 698 | "cell_type": "code", 699 | "execution_count": 38, 700 | "id": "5ca4921a-45a5-4fa1-827f-3e8957a1cdb1", 701 | "metadata": {}, 702 | "outputs": [ 703 | { 704 | "data": { 705 | "text/plain": [ 706 | "dtype('complex128')" 707 | ] 708 | }, 709 | "execution_count": 38, 710 | "metadata": {}, 711 | "output_type": "execute_result" 712 | } 713 | ], 714 | "source": [ 715 | "E.dtype" 716 | ] 717 | }, 718 | { 719 | "cell_type": "markdown", 720 | "id": "6f70b06a-a210-4f33-8156-42a7989e282c", 721 | "metadata": {}, 722 | "source": [ 723 | "by default, interpreter assigns 128 bits ( 16 bytes) for complex data (64 bit for real part and 64 bits for imaginery part). " 724 | ] 725 | }, 726 | { 727 | "cell_type": "code", 728 | "execution_count": 39, 729 | "id": "d833a319-a184-4dc9-b58b-bced8101095b", 730 | "metadata": {}, 731 | "outputs": [], 732 | "source": [ 733 | "F=np.array(L,dtype='c8') # trying to assign 8 bytes for complex datatype" 734 | ] 735 | }, 736 | { 737 | "cell_type": "code", 738 | "execution_count": 40, 739 | "id": "2fbe1987-eb45-4353-86e9-161db66cf4fb", 740 | "metadata": {}, 741 | "outputs": [ 742 | { 743 | "data": { 744 | "text/plain": [ 745 | "array([[1.+0.j, 2.+0.j, 3.+0.j],\n", 746 | " [4.+0.j, 5.+0.j, 6.+0.j]], dtype=complex64)" 747 | ] 748 | }, 749 | "execution_count": 40, 750 | "metadata": {}, 751 | "output_type": "execute_result" 752 | } 753 | ], 754 | "source": [ 755 | "F" 756 | ] 757 | }, 758 | { 759 | "cell_type": "code", 760 | "execution_count": 66, 761 | "id": "3a99c68b-2590-4a6c-ad08-215f891c0f91", 762 | "metadata": {}, 763 | "outputs": [], 764 | "source": [ 765 | "F1=np.array(L,dtype='c16') # another way to assign 16 byte complex data" 766 | ] 767 | }, 768 | { 769 | "cell_type": "code", 770 | "execution_count": 67, 771 | "id": "a2b37c3b-5cbb-4c5e-9200-22fac6c22e36", 772 | "metadata": {}, 773 | "outputs": [ 774 | { 775 | "ename": "TypeError", 776 | "evalue": "data type 'c4' not understood", 777 | "output_type": "error", 778 | "traceback": [ 779 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 780 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 781 | "Cell \u001b[1;32mIn[67], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m F2\u001b[38;5;241m=\u001b[39m\u001b[43mnp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43marray\u001b[49m\u001b[43m(\u001b[49m\u001b[43mL\u001b[49m\u001b[43m,\u001b[49m\u001b[43mdtype\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mc4\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n", 782 | "\u001b[1;31mTypeError\u001b[0m: data type 'c4' not understood" 783 | ] 784 | } 785 | ], 786 | "source": [ 787 | "F2=np.array(L,dtype='c4')" 788 | ] 789 | }, 790 | { 791 | "cell_type": "markdown", 792 | "id": "6cad03d8-8f7b-49eb-ab26-8941851149e7", 793 | "metadata": {}, 794 | "source": [ 795 | "Complex datatype shall be of either 64 bits or 128 bits. All other formats are invalid" 796 | ] 797 | }, 798 | { 799 | "cell_type": "code", 800 | "execution_count": 41, 801 | "id": "d680802e-9716-48d4-949e-83713ab63f7c", 802 | "metadata": {}, 803 | "outputs": [], 804 | "source": [ 805 | "G=np.array(L,dtype='c') " 806 | ] 807 | }, 808 | { 809 | "cell_type": "code", 810 | "execution_count": 42, 811 | "id": "98d7e56f-f978-4c2f-91c2-1d9c1341301f", 812 | "metadata": {}, 813 | "outputs": [ 814 | { 815 | "data": { 816 | "text/plain": [ 817 | "array([[b'1', b'2', b'3'],\n", 818 | " [b'4', b'5', b'6']], dtype='|S1')" 819 | ] 820 | }, 821 | "execution_count": 42, 822 | "metadata": {}, 823 | "output_type": "execute_result" 824 | } 825 | ], 826 | "source": [ 827 | "G " 828 | ] 829 | }, 830 | { 831 | "cell_type": "markdown", 832 | "id": "58b241ac-dfe5-4528-891a-8a2b45b4f1f7", 833 | "metadata": {}, 834 | "source": [ 835 | "It is evident that 'c' does not act as short form of complex but it is taken as ' character' by the interpreter. \n", 836 | "\n", 837 | "All elements are converted into byte strings. datatype is 'byte String' where each string has only one character (hence S1)." 838 | ] 839 | }, 840 | { 841 | "cell_type": "code", 842 | "execution_count": 43, 843 | "id": "02a1bd2f-775a-4be7-8979-837c28d1325d", 844 | "metadata": {}, 845 | "outputs": [], 846 | "source": [ 847 | "L='Made in India'.split()" 848 | ] 849 | }, 850 | { 851 | "cell_type": "code", 852 | "execution_count": 44, 853 | "id": "41cf894e-0706-4948-abd6-39e50ffd4e4c", 854 | "metadata": {}, 855 | "outputs": [ 856 | { 857 | "data": { 858 | "text/plain": [ 859 | "['Made', 'in', 'India']" 860 | ] 861 | }, 862 | "execution_count": 44, 863 | "metadata": {}, 864 | "output_type": "execute_result" 865 | } 866 | ], 867 | "source": [ 868 | "L" 869 | ] 870 | }, 871 | { 872 | "cell_type": "code", 873 | "execution_count": 45, 874 | "id": "9c810d4a-3ec3-4c35-a722-53ebe71066ce", 875 | "metadata": {}, 876 | "outputs": [ 877 | { 878 | "ename": "ValueError", 879 | "evalue": "setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (3,) + inhomogeneous part.", 880 | "output_type": "error", 881 | "traceback": [ 882 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 883 | "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", 884 | "Cell \u001b[1;32mIn[45], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m H\u001b[38;5;241m=\u001b[39m\u001b[43mnp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43marray\u001b[49m\u001b[43m(\u001b[49m\u001b[43mL\u001b[49m\u001b[43m,\u001b[49m\u001b[43mdtype\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mc\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n", 885 | "\u001b[1;31mValueError\u001b[0m: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (3,) + inhomogeneous part." 886 | ] 887 | } 888 | ], 889 | "source": [ 890 | "H=np.array(L,dtype='c')" 891 | ] 892 | }, 893 | { 894 | "cell_type": "code", 895 | "execution_count": 46, 896 | "id": "ef3f4d44-bdc3-4f66-8ba7-6328f4a78dc5", 897 | "metadata": {}, 898 | "outputs": [], 899 | "source": [ 900 | "I=np.array(L)" 901 | ] 902 | }, 903 | { 904 | "cell_type": "code", 905 | "execution_count": 47, 906 | "id": "bcb0cc2a-e87f-4464-90b1-2de95dd811bc", 907 | "metadata": {}, 908 | "outputs": [ 909 | { 910 | "data": { 911 | "text/plain": [ 912 | "array(['Made', 'in', 'India'], dtype=' 1\u001b[0m K\u001b[38;5;241m=\u001b[39m\u001b[43mnp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43marray\u001b[49m\u001b[43m(\u001b[49m\u001b[43mL\u001b[49m\u001b[43m,\u001b[49m\u001b[43mdtype\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mi\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\n", 982 | "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'Made'" 983 | ] 984 | } 985 | ], 986 | "source": [ 987 | "K=np.array(L,dtype='i')" 988 | ] 989 | }, 990 | { 991 | "cell_type": "code", 992 | "execution_count": 51, 993 | "id": "60d6fe8a-dfe1-4ed3-98da-eb8b918c4e02", 994 | "metadata": {}, 995 | "outputs": [], 996 | "source": [ 997 | "M=np.array(L,dtype=bool)" 998 | ] 999 | }, 1000 | { 1001 | "cell_type": "code", 1002 | "execution_count": 52, 1003 | "id": "2c56897b-569f-4643-8424-62be20a66fa8", 1004 | "metadata": {}, 1005 | "outputs": [ 1006 | { 1007 | "data": { 1008 | "text/plain": [ 1009 | "array([ True, True, True])" 1010 | ] 1011 | }, 1012 | "execution_count": 52, 1013 | "metadata": {}, 1014 | "output_type": "execute_result" 1015 | } 1016 | ], 1017 | "source": [ 1018 | "M" 1019 | ] 1020 | }, 1021 | { 1022 | "cell_type": "code", 1023 | "execution_count": 53, 1024 | "id": "123d5931-f25a-47fd-8898-20900c7c7ad2", 1025 | "metadata": {}, 1026 | "outputs": [ 1027 | { 1028 | "data": { 1029 | "text/plain": [ 1030 | "1" 1031 | ] 1032 | }, 1033 | "execution_count": 53, 1034 | "metadata": {}, 1035 | "output_type": "execute_result" 1036 | } 1037 | ], 1038 | "source": [ 1039 | "M.ndim" 1040 | ] 1041 | }, 1042 | { 1043 | "cell_type": "code", 1044 | "execution_count": 54, 1045 | "id": "7ddc091e-a362-489c-9c1a-d9df6a1c5d5a", 1046 | "metadata": {}, 1047 | "outputs": [ 1048 | { 1049 | "data": { 1050 | "text/plain": [ 1051 | "dtype('bool')" 1052 | ] 1053 | }, 1054 | "execution_count": 54, 1055 | "metadata": {}, 1056 | "output_type": "execute_result" 1057 | } 1058 | ], 1059 | "source": [ 1060 | "M.dtype" 1061 | ] 1062 | }, 1063 | { 1064 | "cell_type": "code", 1065 | "execution_count": 55, 1066 | "id": "4c69c3c8-3ee5-4c1a-8560-f49f0ada732e", 1067 | "metadata": {}, 1068 | "outputs": [], 1069 | "source": [ 1070 | "L=[1,2,3,4]" 1071 | ] 1072 | }, 1073 | { 1074 | "cell_type": "code", 1075 | "execution_count": 57, 1076 | "id": "82257b64-9417-4bfb-8860-6ff9a9955659", 1077 | "metadata": {}, 1078 | "outputs": [], 1079 | "source": [ 1080 | "MM=np.array(L,dtype='?')" 1081 | ] 1082 | }, 1083 | { 1084 | "cell_type": "code", 1085 | "execution_count": 58, 1086 | "id": "ddaf49ef-79fc-4c1e-adad-9734cd1583a6", 1087 | "metadata": {}, 1088 | "outputs": [ 1089 | { 1090 | "data": { 1091 | "text/plain": [ 1092 | "array([ True, True, True, True])" 1093 | ] 1094 | }, 1095 | "execution_count": 58, 1096 | "metadata": {}, 1097 | "output_type": "execute_result" 1098 | } 1099 | ], 1100 | "source": [ 1101 | "MM" 1102 | ] 1103 | }, 1104 | { 1105 | "cell_type": "code", 1106 | "execution_count": 59, 1107 | "id": "8fe6f427-530f-427d-a87d-d71f09b76625", 1108 | "metadata": {}, 1109 | "outputs": [ 1110 | { 1111 | "data": { 1112 | "text/plain": [ 1113 | "(2, 3)" 1114 | ] 1115 | }, 1116 | "execution_count": 59, 1117 | "metadata": {}, 1118 | "output_type": "execute_result" 1119 | } 1120 | ], 1121 | "source": [ 1122 | "A.shape" 1123 | ] 1124 | }, 1125 | { 1126 | "cell_type": "code", 1127 | "execution_count": 60, 1128 | "id": "1ed41e1a-4c1b-497b-81d9-04a7d0e50e73", 1129 | "metadata": {}, 1130 | "outputs": [ 1131 | { 1132 | "data": { 1133 | "text/plain": [ 1134 | "(2, 3)" 1135 | ] 1136 | }, 1137 | "execution_count": 60, 1138 | "metadata": {}, 1139 | "output_type": "execute_result" 1140 | } 1141 | ], 1142 | "source": [ 1143 | "B.shape" 1144 | ] 1145 | }, 1146 | { 1147 | "cell_type": "code", 1148 | "execution_count": 61, 1149 | "id": "276ca81b-1952-4ae4-9838-dc966826a03e", 1150 | "metadata": {}, 1151 | "outputs": [ 1152 | { 1153 | "data": { 1154 | "text/plain": [ 1155 | "(3,)" 1156 | ] 1157 | }, 1158 | "execution_count": 61, 1159 | "metadata": {}, 1160 | "output_type": "execute_result" 1161 | } 1162 | ], 1163 | "source": [ 1164 | "M.shape" 1165 | ] 1166 | }, 1167 | { 1168 | "cell_type": "code", 1169 | "execution_count": 62, 1170 | "id": "72b2ff38-1fdf-4fa0-9a2f-d91da287f950", 1171 | "metadata": {}, 1172 | "outputs": [ 1173 | { 1174 | "data": { 1175 | "text/plain": [ 1176 | "(4,)" 1177 | ] 1178 | }, 1179 | "execution_count": 62, 1180 | "metadata": {}, 1181 | "output_type": "execute_result" 1182 | } 1183 | ], 1184 | "source": [ 1185 | "MM.shape" 1186 | ] 1187 | }, 1188 | { 1189 | "cell_type": "code", 1190 | "execution_count": 68, 1191 | "id": "8239969e-8914-447f-8edf-dd1ee33c9c09", 1192 | "metadata": {}, 1193 | "outputs": [], 1194 | "source": [ 1195 | "N=np.asarray(L)" 1196 | ] 1197 | }, 1198 | { 1199 | "cell_type": "code", 1200 | "execution_count": 69, 1201 | "id": "01a39183-965c-45fa-ae5c-4eac8d4a732a", 1202 | "metadata": {}, 1203 | "outputs": [ 1204 | { 1205 | "data": { 1206 | "text/plain": [ 1207 | "array([1, 2, 3, 4])" 1208 | ] 1209 | }, 1210 | "execution_count": 69, 1211 | "metadata": {}, 1212 | "output_type": "execute_result" 1213 | } 1214 | ], 1215 | "source": [ 1216 | "N" 1217 | ] 1218 | }, 1219 | { 1220 | "cell_type": "code", 1221 | "execution_count": 70, 1222 | "id": "b8a1616a-b8ed-4d00-b00f-4826c589f735", 1223 | "metadata": {}, 1224 | "outputs": [ 1225 | { 1226 | "data": { 1227 | "text/plain": [ 1228 | "dtype('int32')" 1229 | ] 1230 | }, 1231 | "execution_count": 70, 1232 | "metadata": {}, 1233 | "output_type": "execute_result" 1234 | } 1235 | ], 1236 | "source": [ 1237 | "N.dtype" 1238 | ] 1239 | }, 1240 | { 1241 | "cell_type": "code", 1242 | "execution_count": 71, 1243 | "id": "233bf2ae-5b7f-44b5-b98c-43ff24e45b31", 1244 | "metadata": {}, 1245 | "outputs": [ 1246 | { 1247 | "data": { 1248 | "text/plain": [ 1249 | "1" 1250 | ] 1251 | }, 1252 | "execution_count": 71, 1253 | "metadata": {}, 1254 | "output_type": "execute_result" 1255 | } 1256 | ], 1257 | "source": [ 1258 | "N.ndim" 1259 | ] 1260 | }, 1261 | { 1262 | "cell_type": "code", 1263 | "execution_count": 72, 1264 | "id": "0c7c19ad-ce35-4d8b-b642-f94f8ec881b9", 1265 | "metadata": {}, 1266 | "outputs": [ 1267 | { 1268 | "data": { 1269 | "text/plain": [ 1270 | "(4,)" 1271 | ] 1272 | }, 1273 | "execution_count": 72, 1274 | "metadata": {}, 1275 | "output_type": "execute_result" 1276 | } 1277 | ], 1278 | "source": [ 1279 | "N.shape" 1280 | ] 1281 | }, 1282 | { 1283 | "cell_type": "markdown", 1284 | "id": "121e71c4-0423-47f5-ac7e-72b3297e6f87", 1285 | "metadata": {}, 1286 | "source": [ 1287 | "Similar to array () function, there is a function 'asarray() in numpy. It will also construct array from the given list, tuple. But if the input is already an array, asarray will generate a pointer to the existing array ( shallow copy). np.array() will always construct a new array object (deep copy)" 1288 | ] 1289 | }, 1290 | { 1291 | "cell_type": "code", 1292 | "execution_count": 73, 1293 | "id": "bf7777a9-9066-4b0e-887e-0db2dc34517e", 1294 | "metadata": {}, 1295 | "outputs": [], 1296 | "source": [ 1297 | "P=np.asarray(N)" 1298 | ] 1299 | }, 1300 | { 1301 | "cell_type": "code", 1302 | "execution_count": 74, 1303 | "id": "cd96cdae-ee64-4844-befb-42dffddedb1b", 1304 | "metadata": {}, 1305 | "outputs": [ 1306 | { 1307 | "data": { 1308 | "text/plain": [ 1309 | "array([1, 2, 3, 4])" 1310 | ] 1311 | }, 1312 | "execution_count": 74, 1313 | "metadata": {}, 1314 | "output_type": "execute_result" 1315 | } 1316 | ], 1317 | "source": [ 1318 | "P" 1319 | ] 1320 | }, 1321 | { 1322 | "cell_type": "code", 1323 | "execution_count": 75, 1324 | "id": "f21fb1ac-fe85-4433-8491-823a92e55156", 1325 | "metadata": {}, 1326 | "outputs": [ 1327 | { 1328 | "data": { 1329 | "text/plain": [ 1330 | "True" 1331 | ] 1332 | }, 1333 | "execution_count": 75, 1334 | "metadata": {}, 1335 | "output_type": "execute_result" 1336 | } 1337 | ], 1338 | "source": [ 1339 | "P is N" 1340 | ] 1341 | }, 1342 | { 1343 | "cell_type": "code", 1344 | "execution_count": 76, 1345 | "id": "f72ad1fd-2d40-46d7-844f-54830e32694d", 1346 | "metadata": {}, 1347 | "outputs": [ 1348 | { 1349 | "data": { 1350 | "text/plain": [ 1351 | "array([ True, True, True, True])" 1352 | ] 1353 | }, 1354 | "execution_count": 76, 1355 | "metadata": {}, 1356 | "output_type": "execute_result" 1357 | } 1358 | ], 1359 | "source": [ 1360 | "P==N" 1361 | ] 1362 | }, 1363 | { 1364 | "cell_type": "code", 1365 | "execution_count": 77, 1366 | "id": "4d546f83-027b-4d94-b0c6-3b38d2a95fe9", 1367 | "metadata": {}, 1368 | "outputs": [], 1369 | "source": [ 1370 | "Q=np.array(N)" 1371 | ] 1372 | }, 1373 | { 1374 | "cell_type": "code", 1375 | "execution_count": 78, 1376 | "id": "e0f0893c-4a14-493b-94d7-a598544b5fa0", 1377 | "metadata": {}, 1378 | "outputs": [ 1379 | { 1380 | "data": { 1381 | "text/plain": [ 1382 | "array([1, 2, 3, 4])" 1383 | ] 1384 | }, 1385 | "execution_count": 78, 1386 | "metadata": {}, 1387 | "output_type": "execute_result" 1388 | } 1389 | ], 1390 | "source": [ 1391 | "Q" 1392 | ] 1393 | }, 1394 | { 1395 | "cell_type": "code", 1396 | "execution_count": 79, 1397 | "id": "738c03a6-aa85-4cba-9f8c-866a1a770f85", 1398 | "metadata": {}, 1399 | "outputs": [ 1400 | { 1401 | "data": { 1402 | "text/plain": [ 1403 | "False" 1404 | ] 1405 | }, 1406 | "execution_count": 79, 1407 | "metadata": {}, 1408 | "output_type": "execute_result" 1409 | } 1410 | ], 1411 | "source": [ 1412 | "Q is N # 'is' operator checks whether both object names point to the same memory location" 1413 | ] 1414 | }, 1415 | { 1416 | "cell_type": "code", 1417 | "execution_count": 80, 1418 | "id": "dad882f4-0f7f-4592-8ab4-dd971c40e939", 1419 | "metadata": {}, 1420 | "outputs": [ 1421 | { 1422 | "data": { 1423 | "text/plain": [ 1424 | "array([ True, True, True, True])" 1425 | ] 1426 | }, 1427 | "execution_count": 80, 1428 | "metadata": {}, 1429 | "output_type": "execute_result" 1430 | } 1431 | ], 1432 | "source": [ 1433 | "Q==N # '==' function checks element by element identity" 1434 | ] 1435 | }, 1436 | { 1437 | "cell_type": "code", 1438 | "execution_count": null, 1439 | "id": "051c21c4-778f-4824-af79-77a8e3984177", 1440 | "metadata": {}, 1441 | "outputs": [], 1442 | "source": [] 1443 | } 1444 | ], 1445 | "metadata": { 1446 | "kernelspec": { 1447 | "display_name": "Python 3 (ipykernel)", 1448 | "language": "python", 1449 | "name": "python3" 1450 | }, 1451 | "language_info": { 1452 | "codemirror_mode": { 1453 | "name": "ipython", 1454 | "version": 3 1455 | }, 1456 | "file_extension": ".py", 1457 | "mimetype": "text/x-python", 1458 | "name": "python", 1459 | "nbconvert_exporter": "python", 1460 | "pygments_lexer": "ipython3", 1461 | "version": "3.11.4" 1462 | } 1463 | }, 1464 | "nbformat": 4, 1465 | "nbformat_minor": 5 1466 | } 1467 | -------------------------------------------------------------------------------- /Numpy_Python_Cheat_Sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IIIT-Ranchi-CS2001/lectureNotes/1834dd48b44512bab9c99c162235e25c424c9dc7/Numpy_Python_Cheat_Sheet.pdf -------------------------------------------------------------------------------- /Pandas_Cheat_Sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IIIT-Ranchi-CS2001/lectureNotes/1834dd48b44512bab9c99c162235e25c424c9dc7/Pandas_Cheat_Sheet.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CS2001 Lecture Slides 2 | -------------------------------------------------------------------------------- /Student-talks/Dictionary_Anubhav-1026.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "459afca0", 6 | "metadata": {}, 7 | "source": [ 8 | "# Understanding Dictionaries in Python\n", 9 | "\n", 10 | "In Python, a dictionary is a built-in data type that allows you to store key-value pairs. It is an unordered collection, meaning the items do not have a specific order. Dictionaries are highly flexible and are used to store data in a way that can be quickly retrieved using keys." 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "id": "0a7ab672", 16 | "metadata": {}, 17 | "source": [ 18 | "## Creating a Dictionary\n", 19 | "\n", 20 | "You can create a dictionary using curly braces `{}` or the `dict()` constructor. Here’s how:\n", 21 | "\n", 22 | "```python\n", 23 | "# Using curly braces\n", 24 | "my_dict = {'key1': 'value1', 'key2': 'value2'}\n", 25 | "\n", 26 | "# Using dict() constructor\n", 27 | "my_dict = dict(key1='value1', key2='value2')\n", 28 | "```\n", 29 | "\n", 30 | "In both cases, the dictionary will have two key-value pairs: `'key1': 'value1'` and `'key2': 'value2'`." 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 2, 36 | "id": "54d6fd9d", 37 | "metadata": {}, 38 | "outputs": [ 39 | { 40 | "name": "stdout", 41 | "output_type": "stream", 42 | "text": [ 43 | "{'key1': 'value1', 'key2': 'value2'}\n", 44 | "{'key1': 'value1', 'key2': 'value2'}\n" 45 | ] 46 | } 47 | ], 48 | "source": [ 49 | "# Example dictionary\n", 50 | "my_dict = {'key1': 'value1', 'key2': 'value2'}\n", 51 | "print(my_dict)\n", 52 | "my_dict2 = dict(key1 = 'value1',key2 = 'value2')\n", 53 | "print(my_dict2)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "id": "2d40c427", 64 | "metadata": {}, 65 | "source": [ 66 | "## Accessing Values\n", 67 | "\n", 68 | "To access a value in a dictionary, use the key inside square brackets or the `get()` method:\n", 69 | "\n", 70 | "```python\n", 71 | "# Accessing with square brackets\n", 72 | "value = my_dict['key1']\n", 73 | "\n", 74 | "# Accessing with get() method\n", 75 | "value = my_dict.get('key1')\n", 76 | "```\n", 77 | "\n", 78 | "If the key does not exist, accessing with square brackets will raise a `KeyError`, while `get()` will return `None` or a default value if specified." 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 3, 84 | "id": "9b59ca00", 85 | "metadata": {}, 86 | "outputs": [ 87 | { 88 | "name": "stdout", 89 | "output_type": "stream", 90 | "text": [ 91 | "value1\n", 92 | "value2\n" 93 | ] 94 | } 95 | ], 96 | "source": [ 97 | "# Accessing values\n", 98 | "value = my_dict['key1']\n", 99 | "print(value)\n", 100 | "\n", 101 | "value = my_dict.get('key2')\n", 102 | "print(value)\n" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "id": "6175c34f", 108 | "metadata": {}, 109 | "source": [ 110 | "## Adding and Updating Items\n", 111 | "\n", 112 | "To add or update items in a dictionary, use the assignment operator with the key:\n", 113 | "\n", 114 | "```python\n", 115 | "# Adding a new key-value pair\n", 116 | "my_dict['key3'] = 'value3'\n", 117 | "\n", 118 | "# Updating an existing key-value pair\n", 119 | "my_dict['key1'] = 'new_value1'\n", 120 | "```\n", 121 | "\n", 122 | "This will either add a new key-value pair if the key does not exist, or update the value if the key already exists." 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": 4, 128 | "id": "28cfab55", 129 | "metadata": {}, 130 | "outputs": [ 131 | { 132 | "name": "stdout", 133 | "output_type": "stream", 134 | "text": [ 135 | "{'key1': 'new_value1', 'key2': 'value2', 'key3': 'value3'}\n" 136 | ] 137 | } 138 | ], 139 | "source": [ 140 | "# Adding and updating items\n", 141 | "my_dict['key3'] = 'value3'\n", 142 | "my_dict['key1'] = 'new_value1'\n", 143 | "print(my_dict)\n" 144 | ] 145 | }, 146 | { 147 | "cell_type": "markdown", 148 | "id": "4ee7a274", 149 | "metadata": {}, 150 | "source": [ 151 | "## Removing Items\n", 152 | "\n", 153 | "To remove items from a dictionary, you can use the `del` statement or the `pop()` method:\n", 154 | "\n", 155 | "```python\n", 156 | "# Using del\n", 157 | "del my_dict['key1']\n", 158 | "\n", 159 | "# Using pop() method\n", 160 | "value = my_dict.pop('key2')\n", 161 | "```\n", 162 | "\n", 163 | "The `del` statement will remove the key-value pair, while `pop()` will remove it and return the value." 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 10, 169 | "id": "f9bc512e", 170 | "metadata": {}, 171 | "outputs": [ 172 | { 173 | "ename": "KeyError", 174 | "evalue": "'key1'", 175 | "output_type": "error", 176 | "traceback": [ 177 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 178 | "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", 179 | "Cell \u001b[0;32mIn[10], line 2\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;66;03m# Removing items\u001b[39;00m\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01mdel\u001b[39;00m my_dict[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mkey1\u001b[39m\u001b[38;5;124m'\u001b[39m]\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28mprint\u001b[39m(my_dict)\n\u001b[1;32m 5\u001b[0m value \u001b[38;5;241m=\u001b[39m my_dict\u001b[38;5;241m.\u001b[39mpop(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mkey2\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mdefault_value\u001b[39m\u001b[38;5;124m'\u001b[39m)\n", 180 | "\u001b[0;31mKeyError\u001b[0m: 'key1'" 181 | ] 182 | } 183 | ], 184 | "source": [ 185 | "# Removing items\n", 186 | "del my_dict['key1']\n", 187 | "print(my_dict)\n", 188 | "\n", 189 | "value = my_dict.pop('key2', 'default_value')\n", 190 | "print(value)\n", 191 | "print(my_dict)\n" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "id": "6d0646dc", 197 | "metadata": {}, 198 | "source": [ 199 | "## Dictionary Methods\n", 200 | "\n", 201 | "Dictionaries come with several useful methods:\n", 202 | "\n", 203 | "- `keys()`: Returns a view of the dictionary's keys.\n", 204 | "- `values()`: Returns a view of the dictionary's values.\n", 205 | "- `items()`: Returns a view of the dictionary's key-value pairs.\n", 206 | "- `clear()`: Removes all items from the dictionary.\n", 207 | "- `copy()`: Returns a shallow copy of the dictionary.\n", 208 | "\n", 209 | "Example:\n", 210 | "\n", 211 | "```python\n", 212 | "keys = my_dict.keys()\n", 213 | "values = my_dict.values()\n", 214 | "items = my_dict.items()\n", 215 | "```\n", 216 | "\n", 217 | "These methods can be useful for iterating over or inspecting the contents of a dictionary." 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": 6, 223 | "id": "c24b86f3", 224 | "metadata": {}, 225 | "outputs": [ 226 | { 227 | "name": "stdout", 228 | "output_type": "stream", 229 | "text": [ 230 | "dict_keys([1, 2])\n", 231 | "dict_values([('Hello', 'helo'), 'world'])\n", 232 | "dict_items([(1, ('Hello', 'helo')), (2, 'world')])\n" 233 | ] 234 | } 235 | ], 236 | "source": [ 237 | "# Dictionary methods\n", 238 | "my_dict = {1:('Hello',\"helo\"),2: 'world'}\n", 239 | "keys = my_dict.keys()\n", 240 | "values = my_dict.values()\n", 241 | "items = my_dict.items()\n", 242 | "print(keys)\n", 243 | "print(values)\n", 244 | "print(items)\n" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "id": "10e1bf6f", 251 | "metadata": {}, 252 | "outputs": [], 253 | "source": [] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": 7, 258 | "id": "791090ec", 259 | "metadata": {}, 260 | "outputs": [ 261 | { 262 | "name": "stdout", 263 | "output_type": "stream", 264 | "text": [ 265 | "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121}\n", 266 | "0 0\n", 267 | "1 1\n", 268 | "2 4\n", 269 | "3 9\n", 270 | "4 16\n", 271 | "5 25\n", 272 | "6 36\n", 273 | "7 49\n", 274 | "8 64\n", 275 | "9 81\n", 276 | "10 100\n", 277 | "11 121\n", 278 | "{1: 2, 2: 3, 3: 4, 4: 2}\n" 279 | ] 280 | } 281 | ], 282 | "source": [ 283 | "s = {x : x**2 for x in range(12)}\n", 284 | "print(s)\n", 285 | "for key,value in s.items():\n", 286 | " print(key,value)\n", 287 | "key1 = [1,2,3,4]\n", 288 | "value1 = [2,3,4,2]\n", 289 | "d = dict(zip(key1,value1))\n", 290 | "print(d)" 291 | ] 292 | }, 293 | { 294 | "cell_type": "markdown", 295 | "id": "6121bd8c", 296 | "metadata": {}, 297 | "source": [ 298 | "## Nested Dictionaries\n", 299 | "```python\n", 300 | "nested_dict = {'outer_key': {'inner_key': 'inner_value'}}\n", 301 | "value = nested_dict['outer_key']['inner_key']\n", 302 | "```\n", 303 | "\n", 304 | "This can be useful for representing more complex data structures." 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": 8, 310 | "id": "e287f64d", 311 | "metadata": {}, 312 | "outputs": [ 313 | { 314 | "name": "stdout", 315 | "output_type": "stream", 316 | "text": [ 317 | "inner_value\n", 318 | "{'outer_key': {'inner_key': 'inner_value'}}\n" 319 | ] 320 | } 321 | ], 322 | "source": [ 323 | "# Nested dictionaries\n", 324 | "nested_dict = {'outer_key': {'inner_key': 'inner_value'}}\n", 325 | "value = nested_dict['outer_key']['inner_key']\n", 326 | "print(value)\n", 327 | "nested2 = nested_dict.copy()\n", 328 | "print(nested2)\n" 329 | ] 330 | }, 331 | { 332 | "cell_type": "code", 333 | "execution_count": null, 334 | "id": "11ea9c5a", 335 | "metadata": {}, 336 | "outputs": [], 337 | "source": [] 338 | }, 339 | { 340 | "cell_type": "markdown", 341 | "id": "5f68b0d3", 342 | "metadata": {}, 343 | "source": [ 344 | "## Conclusion\n", 345 | "\n", 346 | "Dictionaries are a fundamental data type in Python that allow for efficient key-value storage. Understanding how to create, access, modify, and manage dictionaries is crucial for effective programming in Python. Experiment with different dictionary operations to get a better grasp of their capabilities and applications. \n", 347 | "\n", 348 | "- Key-Value Pairs: Stores data as key-value pairs.\n", 349 | "- Ordered (Python 3.7+): Maintains insertion order.\n", 350 | "- Keys Must Be Immutable: Keys must be of immutable types.\n", 351 | "- Values Can Be Any Type: No restriction on the type of values.\n", 352 | "- Mutable: Can be modified in place.\n", 353 | "- No Duplicate Keys: Keys must be unique.\n", 354 | "- Dynamic Size: Can grow or shrink dynamically.\n", 355 | "- Fast Lookup: Provides efficient lookups with O(1) time complexity.\n", 356 | "- Heterogeneous: Allows different types for both keys and values.\n", 357 | "- Comprehensions: Supports dictionary comprehensions for compact construction.\n", 358 | "- Copying: Can create shallow copies using copy() method." 359 | ] 360 | }, 361 | { 362 | "cell_type": "code", 363 | "execution_count": null, 364 | "id": "d33ca3b8", 365 | "metadata": {}, 366 | "outputs": [], 367 | "source": [] 368 | } 369 | ], 370 | "metadata": { 371 | "kernelspec": { 372 | "display_name": "Python 3", 373 | "language": "python", 374 | "name": "python3" 375 | }, 376 | "language_info": { 377 | "codemirror_mode": { 378 | "name": "ipython", 379 | "version": 3 380 | }, 381 | "file_extension": ".py", 382 | "mimetype": "text/x-python", 383 | "name": "python", 384 | "nbconvert_exporter": "python", 385 | "pygments_lexer": "ipython3", 386 | "version": "3.12.4" 387 | } 388 | }, 389 | "nbformat": 4, 390 | "nbformat_minor": 5 391 | } 392 | -------------------------------------------------------------------------------- /Student-talks/Introduction-to-Sets-in-Python-Arjun23-1055.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IIIT-Ranchi-CS2001/lectureNotes/1834dd48b44512bab9c99c162235e25c424c9dc7/Student-talks/Introduction-to-Sets-in-Python-Arjun23-1055.pptx -------------------------------------------------------------------------------- /beginners_python_cheat_sheet_pcc_all.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IIIT-Ranchi-CS2001/lectureNotes/1834dd48b44512bab9c99c162235e25c424c9dc7/beginners_python_cheat_sheet_pcc_all.pdf --------------------------------------------------------------------------------