What general tips do you have for golfing in Python? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Python (e.g. "remove comments" is not an answer).
Please post one tip per answer.
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It only takes a minute to sign up.
Sign up to join this communityWhat general tips do you have for golfing in Python? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Python (e.g. "remove comments" is not an answer).
Please post one tip per answer.
dict.get
as a first-class function# all keys in the dict G with a truthy value
[k for k in G if G[k]]
filter(G.get,G)
# all keys in the dict G with a falsy value
[k for k in G if not G[k]]
G.keys()-filter(G.get,G)
{…, **d}
to merge dict
s in Python 3# merge two dicts
a={…}
b={…}
merged: {**a,**b} # the order lets you decide which overrides which
# set a defaut value
G.setdefault(a,1)
G[a]=G.get(a,1)
G={a:1,**G}
::
# This is a very specific tip when you want to get both an element at
# the near beginning of a list and one somewhere near the end.
# For example, let's assume you want to take the elements at indices 6 and 37
# from a list L of length 40 (it's important it's < 6+37*2)
# ok
a=L[5];b=L[36]
# equivalent
a,b=L[5],L[36]
# 36 = 5 + 31
a,b=L[5::31]
set()
is 5 chars just to create an empty set. If you can have an initial element e
, you can save 2 chars with {e}
.
# assuming the function iterates on its argument
f([x**2 for x in range(4)])
f(x**2 for x in range(4))