Files
learn-python3/notebooks/intermediate/idiomatic_loops.ipynb
2018-06-30 18:25:03 +02:00

387 lines
7.7 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Idiomatic loops"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Looping in general"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = ['John', 'Doe', 'was', 'here']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Don't do it like this. While loops are actually really rarely needed.</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"idx = 0\n",
"while idx < len(data):\n",
" print(data[idx])\n",
" idx += 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Don't do like this either.</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for idx in range(len(data)):\n",
" print(data[idx])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### <font color='green'>Do it like this!</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for item in data:\n",
" print(item)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='green'>If you need the index as well, you can use enumerate.</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for idx, val in enumerate(data):\n",
" print('{}: {}'.format(idx, val))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Looping over a range of numbers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Don't do this.</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"i = 0\n",
"while i < 6:\n",
" print(i)\n",
" i += 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Don't do this either.</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for val in [0, 1, 2, 3, 4, 5]:\n",
" print(val)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### <font color='green'>Do it like this!</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for val in range(6):\n",
" print(val)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reversed looping"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = ['first', 'to', 'last', 'from'] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>This is no good.</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"i = len(data) - 1\n",
"while i >= 0:\n",
" print(data[i])\n",
" i -= 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### <font color='green'>Do it like this!</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for item in reversed(data):\n",
" print(item)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Looping over __n__ collections simultaneously"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"collection1 = ['a', 'b', 'c']\n",
"collection2 = (10, 20, 30, 40, 50)\n",
"collection3 = ['John', 'Doe', True]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Oh boy, not like this.</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"shortest = len(collection1)\n",
"if len(collection2) < shortest:\n",
" shortest = len(collection2)\n",
"if len(collection3) < shortest:\n",
" shortest = len(collection3)\n",
" \n",
"i = 0\n",
"while i < shortest:\n",
" print(collection1[i], collection2[i], collection3[i])\n",
" i += 1\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>This is getting better but there's even a better way!</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"shortest = min(len(collection1), len(collection2), len(collection3))\n",
"for i in range(shortest):\n",
" print(collection1[i], collection2[i], collection3[i])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### <font color='green'>Do it like this!</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for first, second, third in zip(collection1, collection2, collection3):\n",
" print(first, second, third)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='green'>You can also create a dict out of two collections!</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"my_dict = dict(zip(collection1, collection2))\n",
"print(my_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## `for - else` - Checking for a match in a collection\n",
"Let's say we want to verify a certain condition is met by at least one element in a collection. Let's consider the following relatively naive example where we want to verify that at least one item is \"python\" (case insensitive) in `data`. If not, we'll raise a ValueError."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = [1, 2, 3, 'This', 'is', 'just', 'a', 'random', 'Python', 'list']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font color='red'>Don't do it like this</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"found = False\n",
"for val in data:\n",
" if isinstance(val, str):\n",
" if val.lower() == 'python':\n",
" found = True\n",
" break\n",
"if not found:\n",
" raise ValueError(\"Nope, couldn't find.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### <font color='green'>Do it like this!</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for val in data:\n",
" if isinstance(val, str):\n",
" if val.lower() == 'python':\n",
" break\n",
"else:\n",
" raise ValueError(\"Nope, couldn't find.\")"
]
}
],
"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.5.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}