Tips for golfing in Python (original) (raw)
Length tradeoff reference
I've think it would be useful to have a reference for the character count differences for some common alternative ways of doing things, so that I can know when to use which. I'll use _
to indicate an expression or piece of code.
Assign to a variable: +4
x=_;x
_
So, this breaks even if you
- Use
_
a second time:_
has length 5 - Use
_
a third time:_
has length 3
Assign variables separately: 0
x,y=a,b
x=a;y=b
- -2 when
a
equalsb
forx=y=a
Expand lambda
to function def
: +7
lambda x:_
def f(x):return _
- -2 for named functions
- -1 if
_
can touch on the left - -1 in Python 2 if can
print
rather than return - +1 for starred input
*x
Generically, if you're def
to save an expression to a variable used twice, this breaks even when the expression is length 12.
lambda x:g(123456789012,123456789012)
def f(x):s=123456789012;return g(s,s)
STDIN rather than function: +1
def f(x):_;print s
x=input();_;print s
- -1 for line of code needed in
_
if not single-line - +4 if
raw_input
needed in Python 2 - -4 if input variable used only once
- +1 if function must
return
rather thanprint
in Python 2
Use exec
rather than looping over range(n)
: +0
for i in range(n):_
i=0;exec"_;i+=1;"*n
- +2 for Python 3
exec()
- -4 if shifted range
range(c,c+n)
for single-charc
- -5 when going backwards from
n
to1
viarange(n,0,-1)
- -9 if index variable never used
Apply map
manually in a loop: +0
for x in l:y=f(x);_
for y in map(f,l):_
Apply map
manually in a list comprehension: +8
map(f,l)
[f(x)for x in l]
- -12 when
f
must be written in themap
as thelambda
expressionlambda x:f(x)
, causing overall 4 char loss.
Apply filter
manually in a list comprehension: +11
filter(f,l)
[x for x in l if f(x)]
- -1 if
f(x)
expression can touch on the left - -12 when
f
must be written in thefilter
as thelambda
expressionlambda x:f(x)
, causing overall 1 char loss.
_Import versus import single-use: +4*
import _;_.f
from _ import*;f
- Breaks even when
_
has length 5 import _ as x;x.f
is always worse except for multiple imports__import__('_').f
is also worse
Thanks to @Sp3000 for lots of suggestions and fixes.