Categories
Uncategorized

Pretty Python Patterns to Make Your Life Easier

I’m not a natural python programmer. I started off programming in Ruby, where you basically just write what you want to do in English and it somehow always works. Then I moved to JavaScript because it’s the language of the web. But during my master’s degree I wanted to specialize in machine learning, and I wanted to get up to speed quickly.

I didn’t want to waste time fighting with the language. So I started writing Python – quite possibly the highest ROI language there is, i.e. you can get a long done without ever actually having to ‘learn’ it. But coming from JavaScript, I found a lot of things annoying Python.

What follows are my notes on writing better Python. Mostly from hacking my way through LeetCode, but also from patterns I’ve found that just work.


You don’t need .map, .filter, or .reduce

I loved using .reduce() in JavaScript. You can basically do everything with it. But you know what’s even better? List Comprehensions and Dict Comprehensions in Python. Here’s python filtering a list:

And here’s the same principle applied to objects to reshape an object:

You don’t need to map or filter or reduce anything. After you’ve written a few comprehensions they become very readable. I no longer miss functional JavaScript.

Use sorted(), not .sort()

There are a couple of reasons why sorted() is better than .sort() for sorting things:

  • sorted() works on all iterables, not just lists. This means it works on lists, sets, tuples, and anything with a __iter__() method! This makes it far more useful than a method that only works on lists.
  • Mutating data is not cool. sorted() returns a new list (regardless of what you are sorting) whereas .sort() will permanently change the list you are sorting. Not only that, it will then return ‘None’ to you so you can’t even use it inline!

Compare items in a list with range() and len()

The first think you learn in python is that iteration is super easy, and that you should rarely have to use range(len(arr)). But when you have to compare sequential items in a readable way, you can do it like this:


This is an ongoing series where I document python tips that I don’t want to forget.