{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "List comprehension\n", "------------------\n", "\n", "Python offers a compact method called \"list comprehension\" to create lists from lists.\n", "Consider the following case of a list that is processed to create another list:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "iterable=range(5)\n", "my_list=[]\n", "\n", "for x in iterable:\n", " if x<=3:\n", " my_list.append(x**2)\n", "\n", "print (my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using list comprehension this can be done using the following line:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list=[x**2 for x in iterable if x<=3]\n", "\n", "print (my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can see that a loop such as\n", "\n", " for item in iterable:\n", " if conditional:\n", " expression\n", "\n", "is equivalent to\n", "\n", " [expression for item in iterable if conditional]\n", " \n", " \n", "You are always creating a list with list comprehension. If you don't necessarily want a list, a loop can be the simpler option.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 1:\n", "-----------\n", "\n", "Use list comprehension to translate the sentence list\n", "\n", " diogenes=['Cede','paulum','e','sole']\n", "\n", "using the dictionary\n", "\n", " dic={'Cede':'Go','paulum':'a little','e':'out of','sole':'the sun'}\n", " \n", "into an answer sentence list. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# your solution here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 2:\n", "-----------\n", "\n", "Use list comprehension to determine a list with all numbers between 1 and 1000 for which the digit sum is equal to 7." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# your solution here" ] } ], "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.5" } }, "nbformat": 4, "nbformat_minor": 1 }