Lists & comprehensions
A list of dicts, a list comprehension, max with a key function, and an f-string — the core of everyday Python.
users = [
{"name": "Vivek", "role": "admin", "score": 92},
{"name": "Rahul", "role": "editor", "score": 78},
{"name": "Amit", "role": "viewer", "score": 65},
]
names = [user["name"] for user in users]
print(names)
top = max(users, key=lambda user: user["score"])
print(f"Top scorer: {top['name']} with {top['score']}")
total = sum(user["score"] for user in users)
print("Average:", round(total / len(users), 2))
Reading input
Reading and converting input(), then branching on it. Values come from the Input panel, one per line.
name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello, {name}!")
print(f"Next year you turn {age + 1}.")
if age >= 18:
print("You can vote.")
else:
print(f"{18 - age} years to go.")
Classes & dataclasses
A dataclass with a default_factory, a @property, and sorting instances by a computed value.
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
marks: list[int] = field(default_factory=list)
@property
def average(self) -> float:
return sum(self.marks) / len(self.marks) if self.marks else 0.0
def grade(self) -> str:
avg = self.average
if avg >= 90:
return "A"
if avg >= 75:
return "B"
return "C"
students = [
Student("Vivek", [92, 88, 95]),
Student("Rahul", [70, 78, 74]),
Student("Amit", [88, 91, 79]),
]
for student in sorted(students, key=lambda s: s.average, reverse=True):
print(f"{student.name:<8} {student.average:6.2f} {student.grade()}")
Standard library
Counter, defaultdict, json, math and datetime — the standard library doing the heavy lifting.
import json
import math
import random
from collections import Counter, defaultdict
from datetime import date
random.seed(42)
words = "the quick brown fox jumps over the lazy dog the fox".split()
counts = Counter(words)
print("Most common:", counts.most_common(3))
groups = defaultdict(list)
for word in words:
groups[len(word)].append(word)
print("By length:", dict(sorted(groups.items())))
print("Payload:", json.dumps({"pi": round(math.pi, 4), "today": str(date(2026, 8, 24))}))
print("Sample:", random.sample(range(100), 5))
Algorithms practice
Binary search, a palindrome check with a slice reversal, and a Fibonacci generator with yield.
def binary_search(items, target):
low, high = 0, len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
def is_palindrome(text):
cleaned = [char.lower() for char in text if char.isalnum()]
return cleaned == cleaned[::-1]
def fib(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
numbers = sorted([15, 3, 42, 8, 23, 4, 16])
print("Sorted:", numbers)
print("Index of 23:", binary_search(numbers, 23))
print("Palindrome:", is_palindrome("A man, a plan, a canal: Panama"))
print("Fibonacci:", list(fib(100)))