This morning, while reviewing the documentation for lists during exercise 38 in Learn Python 3 the Hard Way, I was inspired to attempt to create a method that would return the counts of each unique element in a list. At a future point I may try to expand it to work with dictionaries as well. While there are built in functions to perform these actions, I thought it would be educational and fun to try to write my own. I started with this idea and just started developing something interactively in iPython as I was alreadying working through parts of LP3THW in it. I thought that the process was interesting enough to document and so here we go.
Developing the Function
I worked interactively in iPython to quickly develop my functions as you can see below. The actual process required more iteration to get working just the way that I wanted, but after completing each part, I used Ctrl + ↑ to jump back through the iPython history and get the finished bits of code I wanted, giving me this:
I now had my code, but only inside of iPython. Additionaly I had been a bit sloppy about name variables while working interactively and things needed to be cleaned up a bit. Cleaning up formatting from copying and pasting from iPython and globally editing variable names are both tasks easy to accomplish in vim.
Creating Finished Script
To begin the work to finished script, I copied the definitions directly from iPython, opened a blank .py file with vim, and pasted the contents in. Now I have my code in a file, but it is messy:
Remove prompt characters
Let’s start by getting rid of the prompt characters with visual block. Go to the first line of the code and hit Ctrl + V to enter visual block. Then use the usual vim navigation to select all of the prompt characters(including the leading space) and then press x to remove them.
Now I wanted to make all my variable names match. You can do this manually, but with vim you can easily search and replace multiple terms. The way I did this in this case was to use / to enter search, then use \ + v enable “very magic” search to enable use of | (“pipe”) to search for multiple terms. Then I used the substitute command with a blank first term to replace instances of the most recent search with the new variable name. In this case these were the commands for vim:
At this point I can add comments or additional functions from in vim and then save as normal. In this post I simply wanted to show the process of going from sketching an idea in iPython to moving to a complete script in vim quickly and efficiently. This write up took considerably longer to write up than it took to create the functions, bring them into vim, clean them up, and export the completed script.