Python Contest Cheat Sheet
- print()
Prints data to the console. Useful for debugging and output.
Example:
print('Hello')
# Output: Hello
- Variables & Typecasting
Store values and convert between types like int, float, str.
Example:
x = '3'
y = int(x) + 2
print(y) # Output: 5
- input()
Reads input from user as a string. Use typecasting to convert.
Example:
name = input('Enter name: ')
print(f'Hi {name}')
- f-Strings
Format strings using variables directly inside curly braces.
Example:
name = 'Ali'
print(f'Hello {name}')
- Arithmetic Operators
Used for math: + - * / // % **
Example:
print(5 + 3, 10 % 3, 2 ** 3)
- := Walrus Operator
Assigns value to a variable inside an expression (Python 3.8+).
Example:
if (n := len('hello')) > 3:
print(n)
- if / elif / else
Conditional branching based on boolean expressions.
Example:
Python Contest Cheat Sheet
if x > 0: print('Positive')
- Loops
for and while loops to repeat actions.
for i in range(3): print(i)
while x < 5: x += 1
- Lists
Ordered, mutable sequences. Supports indexing, appending.
Example:
lst = [1, 2, 3]
lst.append(4)
- List Comprehensions
Create lists concisely.
Example:
[x**2 for x in range(5)]
Conditional: [x for x in lst if x%2==0]
- Dictionaries
Key-value storage. Keys must be unique.
Example:
d = {'a':1}
d['b']=2
- Functions
Reusable code blocks.
Example:
def square(x): return x*x
- Lambda
Anonymous functions for short operations.
Example:
square = lambda x: x*x
- map / filter / reduce
map: apply func to all items
filter: keep items meeting condition
reduce: fold list to one value
Python Contest Cheat Sheet
- Sets
Unordered collections of unique items.
Supports union, intersection.
Example: a & b
- Tuples
Immutable lists.
Example:
t = (1, 2)
print(t[0])
- enumerate()
Returns index and value.
Example:
for i, v in enumerate(lst): print(i, v)
- zip()
Pairs elements from two or more iterables.
Example:
zip([1,2],[3,4]) (1,3), (2,4)
- try / except
Handle exceptions without crashing the program.
Example:
try: 1/0
except ZeroDivisionError: print('Oops')
- sorted() & sort()
sorted() returns new list; sort() modifies original.
Can use key= for custom sort.
- Ternary Operator
One-line if-else.
Example:
result = 'Yes' if cond else 'No'
- reversed() & range()
Reverse iterables and custom ranges.
Python Contest Cheat Sheet
range(5, 0, -1) counts down.
- join() / split()
Convert between string and list.
' '.join(['a','b']) 'a b'
'abc def'.split() ['abc','def']
- defaultdict
Auto-creates keys with default value.
from collections import defaultdict
- Counter
Counts frequency of elements.
from collections import Counter
- set() operations
Find intersection, union, difference of sets.
{1,2} | {2,3} {1,2,3}
- all() / any()
Returns True if all / any elements are True.
all([x>0 for x in lst])
- is vs ==
'is' compares identity; '==' compares value.
[1,2]==[1,2] True, but [1,2] is [1,2] False