{ "cells": [ { "cell_type": "markdown", "id": "e7c60b6d-f52f-4978-88ad-c02812740639", "metadata": {}, "source": [ "###
San Jose State University
Department of Applied Data Science

**DATA 200
Computational Programming for Data Analytics**

Spring 2024
Instructor: Ron Mak
" ] }, { "cell_type": "markdown", "id": "f4afe5d8-98e7-455d-a2c7-a9c16eecf96a", "metadata": {}, "source": [ "# Generator Expressions\n", "#### A ***generator expression*** is similar to a list comprehension, but it creates instead an iterable ***generator object*** that produces values on demand. This an example of the concept of ***lazy evaluation***." ] }, { "cell_type": "code", "execution_count": null, "id": "ef304ed5-24e9-483a-825e-5e830cfd3735", "metadata": {}, "outputs": [], "source": [ "values = list(range(20))\n", "values" ] }, { "cell_type": "markdown", "id": "eeab473e-4471-4e48-adf6-234c64ac4d25", "metadata": {}, "source": [ "### List comprehension: Enclose in square brackets `[` and `]`." ] }, { "cell_type": "code", "execution_count": null, "id": "67ab1320-e906-412c-b4ad-1dfe68ebdf90", "metadata": {}, "outputs": [], "source": [ "squares_of_evens = [v*v for v in values if v%2 == 0]\n", "squares_of_evens" ] }, { "cell_type": "markdown", "id": "9314dba5-c72b-492d-96c1-24e03163525e", "metadata": {}, "source": [ "### Generator: Enclose in parentheses `(` and `)`." ] }, { "cell_type": "code", "execution_count": null, "id": "0e06304b-a34b-4bc8-a7cf-94c993380c33", "metadata": {}, "outputs": [], "source": [ "squares_of_odds = (v*v for v in values if v%2 != 0)\n", "squares_of_odds" ] }, { "cell_type": "code", "execution_count": null, "id": "4a8dced8-1902-4fc1-830e-c26f0d6e8de6", "metadata": {}, "outputs": [], "source": [ "for s in squares_of_odds:\n", " print(s)" ] }, { "cell_type": "code", "execution_count": null, "id": "fd42df0e-2f87-4098-afb7-f9a3c5520c85", "metadata": {}, "outputs": [], "source": [ "for s in squares_of_odds:\n", " print(s)" ] }, { "cell_type": "markdown", "id": "cf250e8f-e09d-443b-82d4-56fe789f6d45", "metadata": {}, "source": [ "#### (c) 2023 by Ronald Mak" ] }, { "cell_type": "code", "execution_count": null, "id": "7384ca06-a376-43cf-8f5e-46332ec38e9c", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 }