Introduction
Python is a popular and easy-to-learn programming language. It is used in many fields such as web development, data analysis, automation, artificial intelligence, and more. This cheatsheet covers the most important and commonly used concepts in Python. It is helpful for beginners and also for experienced developers who want to revise the basics quickly.
1. Variables
Definition : Variables are used to store values.
name = "Alice"
age = 25
Note : You do not need to declare the data type in Python.
2. Data Types
Common types :
int,float,str,bool,list,tuple,dict,set
num = 10 # int
price = 5.5 # float
name = "Tom" # str
is_valid = True # bool
3. Lists
Definition: A list is a collection of items. It is mutable (can be changed).
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[1]) # banana
4. Tuples
Definition: A tuple is similar to a list, but is immutable (cannot be changed).
colors = ("red", "green", "blue")
print(colors[0]) # red
5. Dictionaries
Definition: A dictionary stores data in key-value pairs.
student = {"name": "John", "age": 20}
print(student["name"]) # John
6. Sets
Definition: A set is a collection of unique items.
nums = {1, 2, 3, 2}
print(nums) # {1, 2, 3}
7. Conditional Statements
Used for: Decision making in code.
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
8. Loops
For loop: Used to repeat actions.
for i in range(5):
print(i)
While loop: Runs while a condition is true.
count = 0
while count < 5:
print(count)
count += 1
9. Functions
Definition: A block of code that runs when called.
def greet(name):
print("Hello", name)
greet("Alice")
10. Classes and Objects
Definition: Used in object-oriented programming.
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hi, I am", self.name)
p = Person("David")
p.say_hello()
11. Exception Handling
Used to: Handle errors without stopping the program.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
12. List Comprehension
Definition: A short way to create a new list.
squares = [x*x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
13. Importing Modules
Used to: Use built-in or external code libraries.
import math
print(math.sqrt(16)) # 4.0
14. File Handling
Reading a file
with open("file.txt", "r") as f:
content = f.read()
Writing to a file
with open("file.txt", "w") as f:
f.write("Hello, world")
15. Lambda Functions
Definition : A small anonymous function.
add = lambda x, y: x + y
print(add(3, 5)) # 8
16. Map, Filter, Reduce
map(): Applies a function to all items.
nums = [1, 2, 3]
squared = list(map(lambda x: x*x, nums))
filter(): Filters items based on a condition.
even = list(filter(lambda x: x % 2 == 0, nums))
reduce(): Reduces a list to a single value.
from functools import reduce
total = reduce(lambda x, y: x + y, nums)
17. Global and Local Variables
x = 10 # global
def test():
y = 5 # local
print(x + y)
test()
18. String Formatting
name = "Tom"
age = 20
print(f"My name is {name} and I am {age} years old.")
19. Type Conversion
x = "123"
y = int(x) # converts to integer
20. Built-in Functions
Some common ones:
len(),type(),str(),int(),input(),print(),sum(),sorted()
21. Enumerate
Used to: Get index and value while looping.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)
22. Zip
Used to: Combine multiple iterables (like lists).
names = ["Alice", "Bob"]
scores = [85, 90]
for name, score in zip(names, scores):
print(name, score)
23. Docstrings
Used to: Write documentation inside functions/classes.
def greet():
"""This function prints a greeting"""
print("Hello")
Access using:
print(greet.__doc__)
24. args and kwargs
Used to: Pass a variable number of arguments.
def add(*args):
return sum(args)
def show(**kwargs):
print(kwargs)
add(1, 2, 3)
show(name="Tom", age=30)
25. Virtual Environment (venv)
Used to: Create an isolated environment for a Python project.
python -m venv env
Activate:
env\Scripts\activate(Windows) orsource env/bin/activate(Linux/Mac)
26. List Methods
Common methods:

Join the conversation! Your thoughts help the community grow.