{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyNyEEzMdqD+qPu/0YOpVtei", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "# Optimizing Python Code with List Comprehensions\n", "\n", "## Write faster and cleaner loops the Pythonic way\n", "\n", "| ![space-1.jpg](https://github.com/Tanu-N-Prabhu/Python/blob/master/Img/brecht-corbeel-qHx3w6Gwz9k-unsplash.jpg?raw=true) |\n", "|:--:|\n", "| Photo by Brecht Corbeel on Unsplash|\n", "\n", "\n", "#### Introduction\n", "\n", "When you first learn Python, you’re introduced to `for` loops. They work fine, but once you want faster, cleaner, and more professional-looking code, Python offers a beautiful shortcut called List Comprehensions.\n", "\n", "List comprehensions condense loops into a single line without sacrificing readability, and in many cases, they make your code more intuitive.\n", "\n", "---\n", "\n", "#### What is a List Comprehension?\n", "In simple terms, list comprehension is a concise way to create lists based on existing lists (or any iterable). Instead of writing multiple lines to build a list, you do it all in one elegant line.\n", "\n", "##### Syntax\n", "\n", "```\n", "new_list = [expression for item in iterable if condition]\n", "```\n", "---\n", "\n", "#### Why is it so important\n", "* Cleaner Code: Reduces boilerplate and improves readability.\n", "* Better Performance: Executes faster than traditional for loops.\n", "* Pythonic Style: This shows you understand and embrace Python's philosophy of simplicity.\n", "* Conditional Logic: Easily add conditions inside comprehensions.\n", "* Nesting Possible: You can even nest comprehensions for multidimensional data (carefully!).\n", "\n", "---\n", "\n", "#### Implementation\n", "##### Traditional For Loop\n", "\n", "\n", "\n" ], "metadata": { "id": "xybDgq3b4wRb" } }, { "cell_type": "code", "source": [ "squares = []\n", "for i in range(10):\n", " squares.append(i ** 2)\n", "\n", "squares" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "ryvVtZ935Pki", "outputId": "b1dd9032-ebad-4775-e9aa-489d066c729f" }, "execution_count": 3, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" ] }, "metadata": {}, "execution_count": 3 } ] }, { "cell_type": "markdown", "source": [ "##### Using List Comprehension\n", "\n" ], "metadata": { "id": "Wms5iQ2N5Vdu" } }, { "cell_type": "code", "source": [ "squares = [i ** 2 for i in range(10)]\n", "squares" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "NRPKBNGl5We_", "outputId": "437844cf-83c4-4c46-ff5f-55709d55ef6f" }, "execution_count": 4, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" ] }, "metadata": {}, "execution_count": 4 } ] }, { "cell_type": "markdown", "source": [ "> ***Did you see how shorter and cleaner it is?***\n", "\n", "##### Adding Conditions (Let's step it up)\n", "\n", "Suppose you want only even squares" ], "metadata": { "id": "XcyqfMg_5bJO" } }, { "cell_type": "code", "source": [ "even_squares = [i ** 2 for i in range(10) if i % 2 == 0]\n", "even_squares" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "fCAU8hDg5fzB", "outputId": "b0f803c0-980a-44fe-8543-dd94fa4b893a" }, "execution_count": 5, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[0, 4, 16, 36, 64]" ] }, "metadata": {}, "execution_count": 5 } ] }, { "cell_type": "markdown", "source": [ "> ***This is what called as a one-liner!***\n", "\n", "---\n", "\n", "#### Common Mistakes to Avoid\n", "* **Overcomplicating**: If comprehension looks confusing, use a normal loop instead.\n", "* **Too Many Nestings**: Nesting 2 or more comprehensions can get messy. I prefer breaking into separate steps when needed. Whatever you do, choose wisely!\n", "\n", "---\n", "\n", "#### Fun Fact\n", "List comprehension can be nearly twice as fast as traditional `for` loops because they’re optimized at the C level internally by Python!\n", "\n", "---\n", "\n", "#### Conclusion\n", "List comprehensions are a must-know technique for anyone who wants to write efficient, clean, and Pythonic code. Master them, and you’ll instantly level up the quality (and speed) of your Python scripts. I hope you learned something new today! Suggestions and comments are welcomed in the comment section. Until then, see you next time. Happy Coding!\n", "\n", "---\n", "\n", "#### Before you go\n", "* Be sure to Like and Connect Me\n", "* Follow Me : [Medium](https://medium.com/@tanunprabhu95) | [GitHub](https://github.com/Tanu-N-Prabhu) | [LinkedIn](https://ca.linkedin.com/in/tanu-nanda-prabhu-a15a091b5) | [Python Hub](https://github.com/Tanu-N-Prabhu/Python)\n", "* [Check out my latest articles on Programming](https://medium.com/@tanunprabhu95)\n", "* Check out my [GitHub](https://github.com/Tanu-N-Prabhu) for code and [Medium](https://medium.com/@tanunprabhu95) for deep dives!\n" ], "metadata": { "id": "ccFA7LZx5i0Y" } } ] }