Skip to content

Instantly share code, notes, and snippets.

@chilimangoes
Last active February 1, 2019 20:02
Show Gist options
  • Select an option

  • Save chilimangoes/1ce8991e10792ffaaed6ec416a7b6d8f to your computer and use it in GitHub Desktop.

Select an option

Save chilimangoes/1ce8991e10792ffaaed6ec416a7b6d8f to your computer and use it in GitHub Desktop.
Python Features and Tricks.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Python Features and Tricks.ipynb",
"version": "0.3.2",
"provenance": [],
"collapsed_sections": [],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/chilimangoes/1ce8991e10792ffaaed6ec416a7b6d8f/python-features-and-tricks.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"metadata": {
"id": "RFupl1SWoWA3",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"##Packing and Unpacking"
]
},
{
"metadata": {
"id": "zrnAA2qZA1dC",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"What does the following line of code do in Python?\n",
"\n",
"```python\n",
"a, *b, c = [1, 2, 3, 4, 5, 6]\n",
"```\n",
"\n",
"Or this?\n",
"\n",
"```python\n",
"a = b, c\n",
"```\n",
"\n",
"Or this?\n",
"\n",
"```python\n",
"a, b = some_function()\n",
"```"
]
},
{
"metadata": {
"id": "zg_0olEQBIKC",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Unpacking"
]
},
{
"metadata": {
"id": "OtSTS0df1BdI",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Let's say you have a need to return multiple values from a function. For example, you want to call `get_account_summary()` and return both the account name and ballance. In most languages, you would have to do something like this:\n",
"\n",
"```javascript\n",
"class AccountSummary {\n",
" string AccountName;\n",
" double Ballance;\n",
"}\n",
"\n",
"public AccountSummary get_account_summary() {\n",
" return new AccountSummary() {\n",
" AccountName = \"My Account\",\n",
" Ballance = 1000000.00\n",
" }\n",
"}\n",
"\n",
"var summary = get_account_summary()\n",
"\n",
"print(\"Account Summary:\")\n",
"print(\"----------------\")\n",
"print(summary.AccountName);\n",
"print(summary.Ballance);\n",
"```\n",
"\n",
"In python, you can do it like this:"
]
},
{
"metadata": {
"id": "YD1oNgtJoVue",
"colab_type": "code",
"outputId": "eebe6e8e-133a-42f6-95d8-8e2381367f41",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 85
}
},
"cell_type": "code",
"source": [
"# define a function that returns multiple values\n",
"def get_account_summary():\n",
" return \"My Account\", 1000000.00\n",
"\n",
"# call the function and store in separate variables\n",
"name, ballance = get_account_summary()\n",
"\n",
"print(\"Account Summary:\")\n",
"print(\"----------------\")\n",
"print(name)\n",
"print(ballance)"
],
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"text": [
"Account Summary:\n",
"----------------\n",
"My Account\n",
"1000000.0\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "FYImPCl7v8HD",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"That's unpacking. What about the reverse (packing)?\n",
"\n",
"### Packing"
]
},
{
"metadata": {
"id": "-hhNSv1UqRkE",
"colab_type": "code",
"outputId": "e68f6057-22b3-40cc-9f4a-31ac36499d53",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# packing two values into one variable\n",
"summary = name, ballance\n",
"print(summary)"
],
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"text": [
"('My Account', 1000000.0)\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "zRUb0FYsw_Se",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"###More packing and unpacking...\n",
"\n",
"So what packing and unpacking are doing here is taking automatically 'packing' multiple values (or variables) into a structure (a tuple by default) on the right hand side of a statement or in a return statement, and then automatically 'unpacking' those values from that structure into multiple variables on the left hand side of the statement."
]
},
{
"metadata": {
"id": "0GHWT1AQu12Q",
"colab_type": "code",
"outputId": "3b5ee564-e7a0-4f95-8615-750a4b48ed7e",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 68
}
},
"cell_type": "code",
"source": [
"# set multiple varibles at once\n",
"a, b, c = 1, 2, 3\n",
"print('a =', a)\n",
"print('b =', b)\n",
"print('c =', c)"
],
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"text": [
"a = 1\n",
"b = 2\n",
"c = 3\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "tUSw0faKu7i4",
"colab_type": "code",
"outputId": "a5150c02-6b99-45b3-a0af-c82267d225e8",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 51
}
},
"cell_type": "code",
"source": [
"print('before', a, b)\n",
"\n",
"# swap variables\n",
"b, a = a, b\n",
"\n",
"print('after', a, b)"
],
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"text": [
"before 1 2\n",
"after 2 1\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "uuW0MqAXyUZP",
"colab_type": "code",
"outputId": "69993d06-3d62-470d-f160-2399aa810f10",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 68
}
},
"cell_type": "code",
"source": [
"# Remainders (Python 3)\n",
"a, *b, c = [1, 2, 3, 4, 5, 6]\n",
"\n",
"print('a =', a)\n",
"print('b =', b)\n",
"print('c =', c)\n"
],
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"text": [
"a = 1\n",
"b = [2, 3, 4, 5]\n",
"c = 6\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "fTKNqm_SoheR",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 68
},
"outputId": "185d4adc-330a-4670-a773-fa14beec748c"
},
"cell_type": "code",
"source": [
"# uppacking a tuple\n",
"a, b, c = (1, 2, 3)\n",
"\n",
"print('a =', a)\n",
"print('b =', b)\n",
"print('c =', c)"
],
"execution_count": 6,
"outputs": [
{
"output_type": "stream",
"text": [
"a = 1\n",
"b = 2\n",
"c = 3\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "e9Hdy5JRo2gK",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 68
},
"outputId": "00c29a32-c1f0-4a97-9621-4a40cf2feadb"
},
"cell_type": "code",
"source": [
"# uppacking a dictionary\n",
"# (note this doesn't do what you might intuitively think it does!)\n",
"a, b, c = { 'x':1, 'y':2, 'z':3 }\n",
"\n",
"print('a =', a)\n",
"print('b =', b)\n",
"print('c =', c)"
],
"execution_count": 7,
"outputs": [
{
"output_type": "stream",
"text": [
"a = x\n",
"b = y\n",
"c = z\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "F6w9DqFypD0M",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 68
},
"outputId": "bb6a6ec5-0a39-43b7-e4de-b52b45c6cb08"
},
"cell_type": "code",
"source": [
"# uppacking a list\n",
"a, b, c = [1, 2, 3]\n",
"\n",
"print('a =', a)\n",
"print('b =', b)\n",
"print('c =', c)"
],
"execution_count": 8,
"outputs": [
{
"output_type": "stream",
"text": [
"a = 1\n",
"b = 2\n",
"c = 3\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "rHgw62kE1lA4",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## List Slices"
]
},
{
"metadata": {
"id": "mL_nfC2KQhZ5",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Basic slicing syntax:\n",
"```python\n",
"mylist[start:end:step]\n",
"```\n",
"\n",
"*Potentially confusing detail about `start` and `end`: The above returns a slice of the data from the `start` index, up to **but not including** the `end` index.*"
]
},
{
"metadata": {
"id": "sKMk0Zn_DpLv",
"colab_type": "code",
"outputId": "dfb16c4f-5cd9-4fd2-b90a-110dd94da7ae",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# start out with a list of numbers from 0 to 9\n",
"a = [x for x in range(10)]\n",
"print('a = ', a)"
],
"execution_count": 9,
"outputs": [
{
"output_type": "stream",
"text": [
"a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "tL0TFVfaGi2S",
"colab_type": "code",
"outputId": "b45510e5-d4d5-4fcd-8936-a9d987d552b4",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"a[1:5]"
],
"execution_count": 10,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[1, 2, 3, 4]"
]
},
"metadata": {
"tags": []
},
"execution_count": 10
}
]
},
{
"metadata": {
"id": "lP1N2dCSEnbE",
"colab_type": "code",
"outputId": "9550ff7d-4a9e-4358-88c1-69526eee9b9a",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"a[:3]"
],
"execution_count": 11,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[0, 1, 2]"
]
},
"metadata": {
"tags": []
},
"execution_count": 11
}
]
},
{
"metadata": {
"id": "5n0HSouEF5U2",
"colab_type": "code",
"outputId": "7480a337-83ec-42d6-c469-1f4b288e9c0d",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"a[4::2]"
],
"execution_count": 12,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[4, 6, 8]"
]
},
"metadata": {
"tags": []
},
"execution_count": 12
}
]
},
{
"metadata": {
"id": "C4Grt65Y121x",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Negative Indexing"
]
},
{
"metadata": {
"id": "Ka8JUE1_GTk3",
"colab_type": "code",
"outputId": "9cd64e42-8375-4295-c8e3-7866669af5bb",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# start out with a list of numbers from 1 to 10...\n",
"a = [x for x in range(1, 11)]\n",
"print('a = ', a)"
],
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"text": [
"a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "erPZcM-jGsQ6",
"colab_type": "code",
"outputId": "f2b6b646-26cf-4cad-f557-98831b2d9861",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# retrieve an element starting from the end\n",
"a[-1]"
],
"execution_count": 14,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"10"
]
},
"metadata": {
"tags": []
},
"execution_count": 14
}
]
},
{
"metadata": {
"id": "ZNE9LvmBHAwb",
"colab_type": "code",
"outputId": "58778946-ef6d-4e41-96f0-edbc636e4887",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"a[-3]"
],
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"8"
]
},
"metadata": {
"tags": []
},
"execution_count": 15
}
]
},
{
"metadata": {
"id": "Z9AYoKLAHcOu",
"colab_type": "code",
"outputId": "62a10031-c177-43d7-d174-e1d749f8ba85",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# slices with negative indexing\n",
"a[-5:-2]"
],
"execution_count": 16,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[6, 7, 8]"
]
},
"metadata": {
"tags": []
},
"execution_count": 16
}
]
},
{
"metadata": {
"id": "ez0XvBUPHcUF",
"colab_type": "code",
"outputId": "cc682cf2-5647-419e-bbb2-2b59035909a7",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"a[-2:-5] # this does NOT work"
],
"execution_count": 17,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[]"
]
},
"metadata": {
"tags": []
},
"execution_count": 17
}
]
},
{
"metadata": {
"id": "uZr-OwFMHcbe",
"colab_type": "code",
"outputId": "474a2d2f-c799-45b1-85e9-bcc1f3efd9d6",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"a[-2:-5:-1] # but this does"
],
"execution_count": 18,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[9, 8, 7]"
]
},
"metadata": {
"tags": []
},
"execution_count": 18
}
]
},
{
"metadata": {
"id": "CYgCxUVMIMmD",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## List Slice Assignment\n",
"\n",
"Kind of like packing and unpacking, but with list values..."
]
},
{
"metadata": {
"id": "qe5it4ShIbwz",
"colab_type": "code",
"outputId": "8cf492ce-5624-434f-effb-ca301801c7ac",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# start out with a list of numbers from 0 to 9...\n",
"a = [x for x in range(10)]\n",
"print('a = ', a)"
],
"execution_count": 19,
"outputs": [
{
"output_type": "stream",
"text": [
"a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "QEPIYRQ5IoLt",
"colab_type": "code",
"outputId": "4d3e1f3e-b96c-45da-a551-b6630425d287",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# this syntax for assigning an element in a list should be unremarkable...\n",
"a[3] = 33\n",
"\n",
"print('a = ', a)"
],
"execution_count": 20,
"outputs": [
{
"output_type": "stream",
"text": [
"a = [0, 1, 2, 33, 4, 5, 6, 7, 8, 9]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "QddUE4DNLZZ9",
"colab_type": "code",
"outputId": "01c9bb57-d22a-4d00-b24f-b196c3b9c343",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# but Python also allows things like this, to assign multiple values in a list\n",
"a[2:5] = [12, 13]\n",
"\n",
"print('a = ', a)"
],
"execution_count": 21,
"outputs": [
{
"output_type": "stream",
"text": [
"a = [0, 1, 12, 13, 5, 6, 7, 8, 9]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "Pg6lVeMyNp7y",
"colab_type": "code",
"outputId": "86a3623e-2df5-497c-d16b-312a35dbc7d8",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"# shorthand for deleting all but the first and last elements...\n",
"a[1:-1] = []\n",
"\n",
"print('a = ', a)"
],
"execution_count": 22,
"outputs": [
{
"output_type": "stream",
"text": [
"a = [0, 9]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "Mv0D1sFUIoO7",
"colab_type": "code",
"outputId": "2d4da4b3-a9ec-49db-8bb5-9f846103e29c",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 163
}
},
"cell_type": "code",
"source": [
"# however... this does NOT work... unfortunately... :(\n",
"a[2:5] = 100"
],
"execution_count": 23,
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "ignored",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-23-146b6af3d873>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m100\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: can only assign an iterable"
]
}
]
},
{
"metadata": {
"id": "QO-IEIt2ML2s",
"colab_type": "code",
"outputId": "007a1db0-c180-446c-80fd-2ecec929cd57",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 51
}
},
"cell_type": "code",
"source": [
"# we can do the above using list comprehensions... although it's not as nearly clean :(\n",
"\n",
"# but first we need to recreate our original list from 0 to 9...\n",
"a = [x for x in range(10)]\n",
"print('a = ', a)\n",
"\n",
"a = [v if i < 2 or i >= 5 else 100 for i, v in enumerate(a)]\n",
"print('a = ', a)"
],
"execution_count": 24,
"outputs": [
{
"output_type": "stream",
"text": [
"a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"a = [0, 1, 100, 100, 100, 5, 6, 7, 8, 9]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "g_rrlrStywwy",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## List Comprehensions"
]
},
{
"metadata": {
"id": "4J0SK3uG1SRD",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Kind of like LINQ, in that it lets you manipulate lists of objects.\n",
"\n",
"The basic syntax looks like this:\n",
"```python\n",
"new_list = [expression for item in list if condition]\n",
"```\n",
"\n",
"Which is roughly equivalent to the following LINQ syntax:\n",
"```\n",
"var new_list = from item in list\n",
" where condition\n",
" select expression;\n",
"```"
]
},
{
"metadata": {
"id": "s-IjCcbuzHJy",
"colab_type": "code",
"outputId": "903e8ab5-9df6-4d6c-cba3-68a64c3e875e",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 51
}
},
"cell_type": "code",
"source": [
"# basic syntax\n",
"data = [x for x in range(10)]\n",
"print('data ', data)\n",
"print('even numbers', [x for x in data if x % 2 == 0])"
],
"execution_count": 25,
"outputs": [
{
"output_type": "stream",
"text": [
"data [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"even numbers [0, 2, 4, 6, 8]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "L9hAtbTKEt63",
"colab_type": "code",
"outputId": "4d88572e-c653-44e7-8ee8-ec48f4f36d56",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 51
}
},
"cell_type": "code",
"source": [
"# with complex values and packing/unpacking\n",
"dictionary = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }\n",
"print('dictionary ', dictionary)\n",
"\n",
"inverted_dictionary = { v: k for k, v in dictionary.items()}\n",
"print('inverted_dictionary', inverted_dictionary)"
],
"execution_count": 26,
"outputs": [
{
"output_type": "stream",
"text": [
"dictionary {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}\n",
"inverted_dictionary {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "9gWegVxunnod",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Zipping and Unzipping"
]
},
{
"metadata": {
"id": "nQI8gGSEnzOl",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Combine multiple lists into one"
]
},
{
"metadata": {
"id": "x87vcfFlnq2p",
"colab_type": "code",
"outputId": "ec0657b1-4292-45b6-e575-701b40b957c2",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"numbers = [1, 2, 3, 4, 5]\n",
"names = ['one', 'two', 'three', 'four', 'five']\n",
"\n",
"merged = zip(numbers, names)\n",
"print(set(merged))"
],
"execution_count": 27,
"outputs": [
{
"output_type": "stream",
"text": [
"{(1, 'one'), (4, 'four'), (2, 'two'), (5, 'five'), (3, 'three')}\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "tN-OWPeRnsEG",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## itertools"
]
},
{
"metadata": {
"id": "5R_-vWzMtu1q",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"`itertools` is a module in the standard Python library that exposes handy tools for working with lists.\n",
"\n",
"For example, `combinations` is an easy way to generate all possible combinations from a list..."
]
},
{
"metadata": {
"id": "29ilk9f0z75M",
"colab_type": "code",
"colab": {}
},
"cell_type": "code",
"source": [
"import itertools"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "nDZt3n3yu-R_",
"colab_type": "code",
"outputId": "87a1b966-a685-4e36-c87e-6f9fe0fb86b0",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 119
}
},
"cell_type": "code",
"source": [
"# all possible combinations of 2 numbers from the list 1..4\n",
"for c in itertools.combinations([1, 2, 3, 4], 2):\n",
" print(c)"
],
"execution_count": 29,
"outputs": [
{
"output_type": "stream",
"text": [
"(1, 2)\n",
"(1, 3)\n",
"(1, 4)\n",
"(2, 3)\n",
"(2, 4)\n",
"(3, 4)\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "_cEmCrAXzQK6",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"Cartesian `product` is similar, but more flexible because it gives you all possible combinations from **multiple** lists..."
]
},
{
"metadata": {
"id": "DXiNG87lzl-T",
"colab_type": "code",
"outputId": "825cfa4d-343e-4c6c-b9c6-2488709b2220",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 221
}
},
"cell_type": "code",
"source": [
"list1, list2, list3 = [1, 2, 3], [4, 5], [6, 7]\n",
"\n",
"for p in itertools.product(list1, list2, list3):\n",
" print(p)"
],
"execution_count": 30,
"outputs": [
{
"output_type": "stream",
"text": [
"(1, 4, 6)\n",
"(1, 4, 7)\n",
"(1, 5, 6)\n",
"(1, 5, 7)\n",
"(2, 4, 6)\n",
"(2, 4, 7)\n",
"(2, 5, 6)\n",
"(2, 5, 7)\n",
"(3, 4, 6)\n",
"(3, 4, 7)\n",
"(3, 5, 6)\n",
"(3, 5, 7)\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "-vO7vK8H1WcI",
"colab_type": "code",
"outputId": "b9d71aa6-e990-4bd9-b5c0-52a12dfa13bf",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 289
}
},
"cell_type": "code",
"source": [
"# all 4 bit combinations\n",
"bits = [0, 1]\n",
"for p in itertools.product(bits, repeat=4):\n",
" print(''.join(str(x) for x in p))"
],
"execution_count": 31,
"outputs": [
{
"output_type": "stream",
"text": [
"0000\n",
"0001\n",
"0010\n",
"0011\n",
"0100\n",
"0101\n",
"0110\n",
"0111\n",
"1000\n",
"1001\n",
"1010\n",
"1011\n",
"1100\n",
"1101\n",
"1110\n",
"1111\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "xnGlRi6ivTFQ",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"`chain` allows you to concatenate multiple lists together..."
]
},
{
"metadata": {
"id": "oiKZoNVivKGN",
"colab_type": "code",
"outputId": "11e8265c-cf50-4a64-9f17-3a2a11709386",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"list1 = [1, 2, 3, 4, 5, 6, 7]\n",
"list2 = range(8, 18)\n",
"\n",
"concatenated = [x for x in itertools.chain(list1, list2)]\n",
"print(concatenated)"
],
"execution_count": 32,
"outputs": [
{
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "Eet4aGM9uoHQ",
"colab_type": "code",
"outputId": "8603fdc0-b59c-4703-888b-ca05c1334a99",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 272
}
},
"cell_type": "code",
"source": [
"# use `chain` and `combinations` to get \n",
"# all possible combinations of 1, 2, 3, or 4 numbers from the list 1..4\n",
"all_combinations = [itertools.combinations([1, 2, 3, 4], n) for n in range(1, 5)]\n",
"for c in itertools.chain.from_iterable(all_combinations):\n",
" print(c)"
],
"execution_count": 33,
"outputs": [
{
"output_type": "stream",
"text": [
"(1,)\n",
"(2,)\n",
"(3,)\n",
"(4,)\n",
"(1, 2)\n",
"(1, 3)\n",
"(1, 4)\n",
"(2, 3)\n",
"(2, 4)\n",
"(3, 4)\n",
"(1, 2, 3)\n",
"(1, 2, 4)\n",
"(1, 3, 4)\n",
"(2, 3, 4)\n",
"(1, 2, 3, 4)\n"
],
"name": "stdout"
}
]
},
{
"metadata": {
"id": "b-9YfJPvQDp7",
"colab_type": "code",
"cellView": "both",
"outputId": "b51e3e5a-ab51-4c4a-880b-811d9917e53b",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 34
}
},
"cell_type": "code",
"source": [
"print(\"That's all folks!\")"
],
"execution_count": 34,
"outputs": [
{
"output_type": "stream",
"text": [
"That's all folks!\n"
],
"name": "stdout"
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment