Code Golf in Python refers to attempting to solve a problem using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters “wins”.
Python is a fantastic language for code golfing due to backward compatibility, quirks, it being a high-level language, and all the coercion. So, here we will look at some Code golfing techniques in Python language.
Using loops
Collapse two numerical loops: Suppose you are iterating over a matrix of m rows and n columns . Instead of two nested for loops, one for the row and one of the columns, it’s usually shorter to use a single loop to iterate over the m*n matrix.
Original Code :
m = n = 3
for i in range(m):
for j in range(n):
print(i, j)
Golfed Code :
m = n = 3
for i in range(m*n):
print(i//n, i%n)
This technique is not limited to only two nested loops, we can even write the same loop for 3 or more nested loops
m, n, o = 2, 3, 4
for k in range(m*n*o):
print(k//n//o, k%(n*o), k%o)
Using operators
- Addition or Subtraction by 1: For integer n you can write
-~nis equivalent ton+1~-nis equivalent ton-1- Membership in Set: We write set in Python as S = {1, 2, 3, 4, 5}. To check whether an element e exist in Set S or not we can check the condition as {e}&S
Original Code:
S = {1, 2, 3, 4, 5, 6, 7} if 5 in S: print("Present") else: print("Absent")Golfed Code:
S = {1, 2, 3, 4, 5, 6, 7} if {5}&S: print("Present") else: print("Absent") - Sibling of AND operator: When we have two boolean or integer values, a and b, if we want to find out if both a and b are true, use
*instead ofand.Original Code:
if a and b: print("geeks") else: print("geeksforgeeks")Golfed Code:
if a*b: print("geeks") else: print("geeksforgeeks") - Sibling of OR operator: When we have two boolean or integer values, a and b, if we want to find out if any one from a and b is true or both, use
|instead ofor.Original Code:
if a or b: print("geeks") else: print("geeksforgeeks")Golfed Code:
if a|b: print("geeks") else: print("geeksforgeeks") - Use += instead of append: Instead of using append for adding one item to an existing list, we can use
+=operator.Original Code:
A.append(B)
Golfed Code:
A+=B,
Note: B, here creates a one-element tuple which can be used to extend A just like
[B] in A+=[B]. - Use += instead of extend: Instead of using extend for mergind one list into another at the end, we can use
+=operator.Original Code:
A.extend(B)
Golfed Code:
A+=B
- Magical Comparison Operators: We face many situations in which we have to compare a single variable with different values, and generally we defend them by different comparisons and combining them with AND operator. But Python allows us to put all comparison operators in a single line without using the AND operator.
Original Code:if a>1 and a<10: print(a)Golfed Code:
if 1<a<10: print(a)Note: We can use this technique for multiple variable also at the same time.
Original Code:if a > 10 and b > 10 and 30 > a and 50 > b: print(a)Golfed Code:
if 30 > a > 10 < b < 50: print(a)
This works because the bit flip ~x equals -x-1. This uses the same number of characters, but can indirectly cut spaces or parens for operator precedence.
Using Functions
- Sibling of Floor function: Suppose we want to find the floor value of a real number, we generally import floor function from math and then apply on the number. But we can simply apply the floor division with 1, which will give us a fruitful result.
Original Code:
from math import floor n = 3/2 print(floor(n))
Golfed Code:
n = 3/2 print(n//1)
Original Code:
from math import ceil n = 3/2 print(ceil(n))
Golfed Code:
n = 3/2 print(-(-n//1))
Original Code:
def c(a): if a < 3: return a-5 else: return a+5
Golfed Code:
c=lambda a:a<3and a-5or a+5
Original code:
string = 'abcdefghijklmnopqrstuvwxyz' or string = [chr(i+97)for i in range(26)]
Golfed Code:
string = map(chr,range(97,123))
Using indexing
- Indexing Technique for conditions: When we have a certain condition which will give the answer in the form of small integers then we can use that in integer index in list or tuple to get our final answer.
Original Code:
if a<b:return a else:return b
Golfed Code:
return (b, a)[a<b]
Original Code:
string = 'geeksforgeeks'
for i in range(len(string)-1,-1,-1):
print(string[i])
Golfed Code:
string = 'geeksforgeeks'
for i in string[::-1]:
print(i)
L[~i] to get the i’th element from the back. This is the i’th element of the reverse of L. The bit complement ~i equals -i-1, and so fixes the off-by-one error from L[-i].
Original Code:
string = 'geeksforgeeks'
for i in range(len(string)-1,-1,-1):
print(string[i])
Golfed Code:
for i in range(len(string)):
print(string[~i])
* operator with the name of the list instead of looping through the list.
Original Code:
A = [1,2,3,4,5,6,7]
for i in A:
print(i,end = ' ')
Golfed Code:
A = [1,2,3,4,5,6,7] print(*A)
Using assignment
- Assigning the same values to multiple variables: We can assign the same value to multiple variables either in a single line or multiple lines.
Original Code:
# multiple lines a = 0 b = 0 c = 0 # single line a,b,c = 0,0,0
Golfed Code:
a = b = c = 0
Original Code:
# multiple lines a = 'p' b = 'q' c = 'r' # single line a,b,c = 'p','q','r'
Golfed Code:
a,b,c = 'pqr'
Using conversion
- Converting iterables into the list: Imagine you have any ordered iterable like a tuple or string but you want to convert it into a list, so you can do this with * operator.
Original Code:
a = (2,3,5,7,11) x = list(a) a = 'geeksforgeek' x = list(a)
Golfed Code:
a = (2,3,5,7,11) *x, = a a = 'geeksforgeeks' *x, = a
Originial Code:
a = (2,3,5,7,11) x = set(a) a = [2,3,5,7,11] x = set(a) a = 'geeksforgeeks' x = set(a)
Golfed Code:
a = (2,3,5,7,11)
x = {*a}
a = [2,3,5,7,11]
x = {*a}
a = 'geeksforgeeks'
x = {*a}
Originial Code:
a = (2,3,5,7,11) x = tuple(a) a = [2,3,5,7,11] x = tuple(a) a = 'geeksforgeeks' x = tuple(a)
Golfed Code:
a = (2,3,5,7,11) x = (*a,) a = [2,3,5,7,11] x = (*a,) a = 'geeksforgeeks' x = (*a,)
During joining of different iterables
- Joining multiple Lists: We can join the multiple lists using + operator, but for code golfing we can do the same using * operator.
Original Code:
T = [2,3,4,5,6,7,8,9] new_T = [1]+T+[10]
Golfed Code:
T = [2,3,4,5,6,7,8,9] new_T = [1,*T,10]
Original Code:
T = (2,3,4,5,6,7,8,9) new_T = (1,)+T+(10,)
Golfed Code:
T = (2,3,4,5,6,7,8,9) new_T = (1,*T,10)
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
Recommended Posts:
- Code Golfing in JavaScript
- Java Program to Convert Binary Code Into Equivalent Gray Code Using Recursion
- Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
- Packaging and Publishing Python code
- Optimization Tips for Python Code
- Understanding Code Reuse and Modularity in Python 3
- Performing Google Search using Python code
- Morse Code Translator In Python
- How to generate byte code file in python ?
- Execute a String of Code in Python
- Python code to move spaces to front of string in single traversal
- Python code to print common characters of two Strings in alphabetical order
- Code introspection in Python
- Python code to convert SOP to POS
- Python Code for time Complexity plot of Heap Sort
- Python | Generate QR Code using pyqrcode module
- Different Python IDEs and Code Editors
- Debugging Python code using breakpoint() and pdb
- Issues with using C code in Python | Set 1
- Issues with using C code in Python | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

