Comments on Tips for golfing in Python
Parent
Tips for golfing in Python
If you have any tips for golfing in Python, add them as answers to this post.
Use the unpacking `` instead o …
3y ago
If you print some string `s` w …
3y ago
Reorder expressions in order t …
3y ago
Combine conditionals Python …
3y ago
Replace `n+1` with `-n` and `n …
3y ago
Replace if/else expressions by …
3y ago
Use `a+=[b]` instead of `a.app …
3y ago
` == and` If you want to ch …
3y ago
Combine loops Suppose you h …
3y ago
Replace `range()` if $n …
3y ago
Assign `float`s while leaving …
3y ago
Renaming functions A funny, …
3y ago
Use `lambda`s instead of funct …
3y ago
`import` You can import som …
3y ago
Replace print loops by list un …
3y ago
Replace `for` loops with strin …
3y ago
If you have a loop or `if`, yo …
3y ago
`| == or` This bitwise oper …
3y ago
Post
Reorder expressions in order to save whitespace
Consider the following code:
if c=='U':c='X'
The space between if
and c
obviously cannot be removed, as that would merge them to the identifier ifc
. However by reversing the order of the arguments to ==
, the space becomes removable:
if'U'==c:c='X'
As user noted in the comments, another place where whitespace can be saved is between a number and a following keyword. For example, in
if 2+x in{a,b,c}:x=0
the space between x
and in
cannot be simply removed. However reordering the sum allows to remove it anyway:
if x+2in{a,b,c}:x=0
0 comment threads