Python Code Golfing Tricks

Yuval Greenfield
Jul 29, 2018 · 2 min read

In code golfing you have to complete a given task using as few characters as possible.

Please don’t golf at work

The c̵o̵d̵e̵f̵i̵g̵h̵t̵s̵ site runs code golfing competitions daily. Through the leaderboard you can learn techniques in minimizing code.

x + 1 == ~-x

At a glance both sides of that equality have the same amount of characters. But ~-x is useful in calculations where you’d like to avoid parenthesis. E.g. compare

x*(x+1) vs x*~-x

Which takes 7 characters down to 5.

x *= x

Probably the shortest way to square a variable which is 4 characters instead of the 5: x=x*x

Booleans are 1 and 0

You can use booleans in multiplication, and addition (e.g. to increment a counter). Check out this golf by miguel_r35 on codesignal. Two if statements were removed thanks to the predictable numerical boolean value.

# Discover the length of the longest index range that sums
# to less than or equal to `e` (energy)
def roverTour (t, e):
i = len(t) # start off with the maximum possible value
for x in t:
f = x > e # did we run out of energy
e += f*t[-i] - x # using multiply, add when `x > e`
i -= f # decrement using a boolean when `x > e`
return i

Transpose a matrix with zip(*seq)

This can be useful when you need to operate on the columns of a 2D array. Note that in Python 3 zip returns an iterator.

>>> list(zip(*[[1, 2, 3], [4, 5, 6]]))
[(1, 4), (2, 5), (3, 6)]

This solution by dav23r verifies the sum of the columns equals the sum of the rows:

def cols_equal_rows(arr):
for x, y in zip(map(sum, arr), map(sum, zip(*arr))):
if x != y:
return False
return True

Yuval Greenfield

Written by

code + data = progress … DevRel at

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade