{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Python list -> sublist\n", "\n", "# creating a sublist, such as list[10: 14], duplicates the data;\n", "# they then exist in memory twice.\n", "# modifying the sublist does not affect the original list.\n", "\n", "list = [x*x for x in range(16)]\n", "sublist = list[10: 14]\n", "\n", "print(\"list:\", list, sep=\"\\t\\t\")\n", "print(\"sublist:\", sublist, sep=\"\\t\", end=\"\\n\\n\")\n", "\n", "for i in range(len(sublist)):\n", " sublist[i] -= 1\n", "\n", "print(\"list:\", list, sep=\"\\t\\t\")\n", "print(\"sublist:\", sublist, sep=\"\\t\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# numpy array -> view\n", "\n", "# creating an array view, such as array[10: 14],\n", "# creates a new reference to part of the region in memory allocated for the array;\n", "# the data are not copied, they still exist in memory only once.\n", "# therefore, modifications done to the view are reflected in the content of the original array.\n", "\n", "import numpy as np\n", "\n", "array = np.array([x*x for x in range(16)])\n", "view = array[10: 14]\n", "\n", "print(\"array:\", array, sep=\"\\t\")\n", "print(\"view:\", view, sep=\"\\t\", end=\"\\n\\n\")\n", "\n", "for i in range(len(view)):\n", " view[i] -= 1\n", "\n", "print(\"array:\", array, sep=\"\\t\")\n", "print(\"view:\", view, sep=\"\\t\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.10" } }, "nbformat": 4, "nbformat_minor": 4 }