How to use operators In Python
- 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("w3wiki")
Golfed Code:
if a*b: print("geeks") else: print("w3wiki")
- 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("w3wiki")
Golfed Code:
if a|b: print("geeks") else: print("w3wiki")
- 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)
Code Golfing in Python
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.