Skip to content

Instantly share code, notes, and snippets.

@tedmiston
Created July 24, 2017 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tedmiston/edb0f735f6aa3731762f66ea63f8e37f to your computer and use it in GitHub Desktop.
Save tedmiston/edb0f735f6aa3731762f66ea63f8e37f to your computer and use it in GitHub Desktop.
massive destruct-ion
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n"
]
}
],
"source": [
"x = tuple(range(10))\n",
"print(x)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0, 2, 4, 6, 8)\n",
"(1, 3, 5, 7, 9)\n"
]
}
],
"source": [
"evens, odds = x[::2], x[1::2]\n",
"print(evens)\n",
"print(odds)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n",
"7\n"
]
}
],
"source": [
"three, _, seven = x[3:8][::2] # _ = convention for unused vars\n",
"print(three)\n",
"print(seven)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"_, three, _, seven, _ = x[1::2] # it can even be on the lhs multiple times\n",
"three"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 3]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"d = {'a': 1, 'b': 2, 'c': 3}\n",
"\n",
"# me shortly after discovering destructuring in js\n",
"def destruct(a_dict, keys):\n",
" return [a_dict.get(k) for k in keys]\n",
"\n",
"destruct(d, ['a', 'c'])"
]
}
],
"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.2"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment