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
If you have a loop or if
, you can save two or more characters (depending on the current indentation level and the number of statements in the body) by putting it right after the colon:
For example, assume you have this loop with 33 characters:
for x in a:
do_something_with(x)
Since you've got just one statement, you can delete the newline character and the following indentation space, in order to get 31 characters:
for x in a:do_something_with(x)
If the body has more than one statement, those can be separated with semicolon. For example
if (condition):
do_something()
do_more()
becomes
if condition:do_something();do_more()
Thanks to @Moshi for pointing out that it also works with several statements.
0 comment threads