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

Assign variables separately: 0

x,y=a,b
x=a;y=b

Expand lambda to function def: +7

lambda x:_
def f(x):return _

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

Use exec rather than looping over range(n): +0

for i in range(n):_
i=0;exec"_;i+=1;"*n

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]

Apply filter manually in a list comprehension: +11

filter(f,l)
[x for x in l if f(x)]

_Import versus import single-use: +4*

import _;_.f
from _ import*;f

Thanks to @Sp3000 for lots of suggestions and fixes.