Skip to content

Commit

Permalink
Added note on writing loops using indices instead of elements
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Hearin committed Apr 14, 2017
1 parent cdd12e6 commit bf87e30
Showing 1 changed file with 81 additions and 6 deletions.
87 changes: 81 additions & 6 deletions common_gotchas.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,89 @@
"%timeit fast_cython(x, y)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Writing loops the pythonic way"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One very nice feature of python is being able to write loops over array *elements* rather than array *indices*:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"arr = np.arange(5)\n",
"for x in arr:\n",
" print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You may have noticed that all the Cythonized loops written in this repo were over the *indices* of the array, not over its elements:"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"npts = len(arr)\n",
"for i in range(npts):\n",
" print(arr[i])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is purposeful: whenever you do a loop the \"pythonic\" way, you are actually doing some high-level operations in the Python layer that cannot be reduced to an elementary C operation. So when writing loops in Cython, be sure to always do \n",
"\n",
"```\n",
">>> for i in range(some_cdef_integer)\n",
"``` \n",
"\n",
"instead of \n",
"\n",
"```\n",
">>> for element in array\n",
"```"
]
},
{
"cell_type": "code",
Expand Down

0 comments on commit bf87e30

Please sign in to comment.