286
\$\begingroup\$

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.

\$\endgroup\$
9
  • 33
    \$\begingroup\$ Oh, I can see a whole set of questions like this one coming for each language... \$\endgroup\$ – R. Martinho Fernandes Jan 28 '11 at 4:26
  • 6
    \$\begingroup\$ @Marthinho I agree. Just started a C++ equivalent. I don't think its a bad thing though, as long as we don't see the same answers re-posted across many of these question types. \$\endgroup\$ – moinudin Jan 28 '11 at 12:28
  • 58
    \$\begingroup\$ Love the question but I have to keep telling myself "this is ONLY for fun NOT for production code" \$\endgroup\$ – Greg Guida Dec 21 '11 at 0:08
  • 3
    \$\begingroup\$ Shouldn't this question be a community wiki post? \$\endgroup\$ – dorukayhan May 29 '16 at 15:35
  • 4
    \$\begingroup\$ @dorukayhan Nope; it's a valid code-golf tips question, asking for tips on shortening python code for CG'ing purposes. Such questions are perfectly valid for the site, and none of these tags explicitly says that the question should be CW'd, unlike SO, which required CG challenges to be CW'd. Also, writing a good answer, and finding such tips always deserves something, that is taken away if the question is community wiki (rep). \$\endgroup\$ – Erik the Outgolfer Sep 9 '16 at 14:48

151 Answers 151

1 2 3 4 5
6
0
\$\begingroup\$

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 dicts 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}

Extract elements from a list using ::

# 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 literals

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}.

Generators instead of comprehension lists in function calls

# assuming the function iterates on its argument
f([x**2 for x in range(4)])
f(x**2 for x in range(4))
\$\endgroup\$
1 2 3 4 5
6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.