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
- -~n is equivalent to n+1
- ~-n is equivalent to n-1
This works because the bit flip ~x equals -x-1. This uses the same number of characters, but can indirectly cut spaces or parents for operator precedence.
- Membership in Set: We write set in Python as S = {1, 2, 3, 4, 5}. To check whether an element e exists 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 of and.
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 of or.
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 merging 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 variables 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)
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)
- Sibling of Ceil function: Suppose we want to find the ceil value of a real number, we generally import ceil function from math and then apply on the number. But we can do this operation in a more beautiful manner by first multiplying with -1 and then apply floor division with 1 and again multiply with -1.
Original Code:
from math import ceil
n = 3/2
print(ceil(n))
Golfed Code:
n = 3/2
print(-(-n//1))
- Lambda functions: Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.
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
- To get the entire alphabet string: We can use the map function of python to get the string of whole alphabet set.
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]
- Reverse the Sequence: We can reverse any list sequence using the good alien smiley face.
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)
- Use ~ to index from the back of a list: If L is a list, use 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])
- Print the items of the list: We can print the items of a list by using the * 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
- Assigning same or different characters to variable: We can assign the same of different characters to multiple variables either in a single line or multiple lines.
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
- Converting iterables into the Set: Imagine you have any iterable like a list, tuple or string but you want to convert it into a Set, so you can do this with * operator.
Original 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}
- Converting iterables into the Tuple: Imagine you have any iterable like a list, set, or string but you want to convert it into a Tuple, so you can do this with * operator.
Original 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]
- 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)
Similar Reads
Python compile() Function
Python is a high-level, general-purpose, and very popular programming language. In this article, we will learn about the Python compile() function. Python compile() Function SyntaxPython compile() function takes source code as input and returns a code object that is ready to be executed and which ca
3 min read
Declaring an Array in Python
An array is a container used to store the same type of elements such as integer, float, and character type. An Array is one of the most important parts of data structures. In arrays, elements are stored in a contiguous location in a memory. We can access the array elements by indexing from 0 to (siz
4 min read
Powerful One-Liner Python codes
Python is a widely-used general-purpose, high-level programming language. Python programs generally are smaller than other programming languages like Java. Programmers have to type relatively less and indentation requirements of the language makes them readable all the time. However, Python programs
6 min read
Python Print Exception
In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions. Using as keywordas keyword lets u
3 min read
Python 3 - input() function
In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optio
3 min read
Eliminating Loop from Python Code
In general, Loops are a pillar of any programming language. Loops allow us to execute a set of statements multiple times, which is particularly useful when dealing with lists, arrays, and kind of any of iterable. However, loops especially nested loops can slow down your code and affect the overall p
4 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks
2 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
4 min read
Print lists in Python
Printing a list in Python is a common task when we need to visualize the items in the list. There are several methods to achieve this and each is suitable for different situations. In this article we explore these methods. The simplest way of printing a list is directly with the print() function: [G
3 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read