Tips to code golf in Python [Part-1]

Just for fun
3 min readApr 18, 2021

Like in golf, the low score wins, similarly “Code Golf” in Python refers to having the shortest amount of code in terms of “characters” or “bytes”.

Tip #1
Use += instead of append to append something to a list
As an example:

a = [1, 2, 3]
a.append(4)
[1, 2, 3, 4]
# this does the same
a = [1, 2, 3]
a += [4]
[1, 2, 3, 4]

Tip #2
Use List Comprehensions with list indexing to avoid using long if and else statements.

x = 10
if x > 5:
print("X is greater than 5")
else:
print("X is lower than 5")
# this does the same
print(["X is lower than 5", "X is greater than 5"][x>5])
"""
x > 5 evaluates to True, which is a subclass of int `1`
On index 1 is "X is greater than 5", thus it gets printed
"""

Tip #3
In case of comparing two values with 1 and 0 can be lowered by 1 char using < or >
The same goes for checking if some value is equal to or greater than or equal to or lower than

x = 0
if x == 0:
# this does the same
if x<1:
a = 10
if a >= 10:
# this does the same by reducing 1 from the limit
if a>9:
if a <= 10:
# this does the same by adding 1 to the limit
if a<11:

Tip #4
Use 1 space indentation instead of 1 tab or 4 spaces indentation

if some > 10:
print("Hi")
# can be reduced to
if some>10:
print("Hi") # 1 space indentation
# further one liner
if some>10:print("Hi")

Tip #5
Inbuilt methods like dict.get are extremely useful when a default value is needed

t = {"key1": "value"}
if "key2" in t:
print(t["key2"])
else:
print("Not in t")
# can be reduced to
print(t.get("key2","Not in t"))
"""
The syntax for `dict.get()` is
dict.get(key, value_if_key_not_found)
Note: `value_if_key_not_found` defaults to None
"""

Tip #6
Nested for loops using rangecan be converted to a single for loop by using the multiplication * operator

for i in range(a):
for j in range(b):
for h in range(c):
...
# can be reduced to
for i in range(a*b*c):
i, j, h = i//c//b, i//c%b, i%c
# two nested for loops
for i in range(a*b):
i, j = i//b, i%b

Tip #7
Declaring multiple variables in one line

# How kids do it
a = "1"
b = "2"
c = "3"
# How men do it
a,b,c="1","2","3"
# How legends do it
a,b,c="123"
# Take this a meme please

Tip #8
You may have used math.floor and math.ceil several times for easiness and short code but there is a more shorter way to do it

from math import floor, ceil
e = 16/13
print(floor(e))
print(ceil(e))
# can be reduced to
print(e//1)
print(0--e//1))
"""
Note: the shorter code returns a float not an int
"""

Tip #9
Use ; in Python to make your code fit in one line and save indentations spaces/ tabs too

def test():
x = 10
y = 20
print(x, y)
# can be reduced to
def test():x,y=10,20;print(x,y)

Tip #10
Use Python’s inbuilt functions to reduce characters

# `isdigit()`
x = "10"
try:
x = int(x)
except:
pass
# can be reduced to
if x.isdigit():x=int(x)
# `islower()` and `isupper()`
x = "hello world 121212121212"
print(x.islower()) # True
x = "HELLO WORLD 121212121212"
print(x.isupper()) # True

That’s it for this part. Hope you learnt something new today that you didn’t know exists in Python. This may help you to boost your code golfing skills. I will be posting many parts on Code Golfing in Python, so stay alert!
My Github: https://github.com/techguy940

--

--