{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# List Comprehensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## AAM ZINDGI" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 3, 6, 9]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = []\n", "\n", "for i in range(10):\n", " if i%3 == 0:\n", " l.append(i)\n", "l\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MENTOSS ZINDGI" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 3, 6, 9]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[i for i in range(10) if i%3 == 0]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 1, 2, 6, 1, 2, 9]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[i if i%3 == 0 else i%3 for i in range(10)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionary Comprehension\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{0: 'ITEM-0',\n", " 1: 'ITEM-1',\n", " 2: 'ITEM-2',\n", " 3: 'ITEM-3',\n", " 4: 'ITEM-4',\n", " 5: 'ITEM-5',\n", " 6: 'ITEM-6',\n", " 7: 'ITEM-7',\n", " 8: 'ITEM-8',\n", " 9: 'ITEM-9'}" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {item:f\"ITEM-{item}\" for item in range(10)}\n", "d " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'ITEM-0': 0,\n", " 'ITEM-1': 1,\n", " 'ITEM-2': 2,\n", " 'ITEM-3': 3,\n", " 'ITEM-4': 4,\n", " 'ITEM-5': 5,\n", " 'ITEM-6': 6,\n", " 'ITEM-7': 7,\n", " 'ITEM-8': 8,\n", " 'ITEM-9': 9}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "{value:key for key,value in d.items()}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Set Comprehensions" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'nishant', 'nishatn', 'nsihatjn', 'nsihatn'}" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "{item for item in [\"nsihatn\",\"nsihatjn\",\"nishatn\",\"nishant\",\"nishant\",\"nishant\",\"nishant\"]}" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.3" } }, "nbformat": 4, "nbformat_minor": 4 }