Skip to content

Instantly share code, notes, and snippets.

@brunurd
Created March 9, 2021 03:46
Show Gist options
  • Save brunurd/e80b3efb2948231b20a1ed840c96f42c to your computer and use it in GitHub Desktop.
Save brunurd/e80b3efb2948231b20a1ed840c96f42c to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "golden-candidate",
"metadata": {},
"source": [
"## Python maps and lists"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "british-forwarding",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"abc\n[1, 4, 9]\n[4]\n"
]
}
],
"source": [
"# lambda\n",
"test = lambda x:print(x)\n",
"test('abc')\n",
"\n",
"# list comprehensions (map)\n",
"list1 = [item ** 2 for item in [1,2,3]]\n",
"\n",
"# list comprehensions (filter)\n",
"list2 = [item ** 2 for item in [1,2,3] if item % 2 == 0]\n",
"\n",
"print(list1)\n",
"print(list2)"
]
},
{
"cell_type": "markdown",
"id": "selective-delay",
"metadata": {},
"source": [
"### Map"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "protecting-pasta",
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[2, 3, 4]"
]
},
"metadata": {},
"execution_count": 2
}
],
"source": [
"plus_one = lambda n: n + 1 ; l = [1, 2, 3]\n",
"\n",
"list(map(plus_one, l))"
]
},
{
"cell_type": "markdown",
"id": "acquired-display",
"metadata": {},
"source": [
"### Filter"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "artistic-divorce",
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[2, 4]"
]
},
"metadata": {},
"execution_count": 3
}
],
"source": [
"is_even = lambda n: n % 2 == 0 ; l = [1,2,3,4]\n",
"\n",
"list(filter(is_even,l))"
]
},
{
"cell_type": "markdown",
"id": "aboriginal-terrain",
"metadata": {},
"source": [
"### Reduce"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "rising-screen",
"metadata": {},
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"6"
]
},
"metadata": {},
"execution_count": 4
}
],
"source": [
"from functools import reduce\n",
"\n",
"l = [1,2,3]\n",
"\n",
"reduce((lambda a, b: a + b), l)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cultural-faculty",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3.8.5 64-bit ('venv')",
"metadata": {
"interpreter": {
"hash": "a198968a07776e1374d5a42b4432cdd7a224fdad7bc7ae0b2a6986d2f1092b96"
}
}
},
"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-final"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment