The 50 Best Python Practice Problems (Beginner to Advanced) — Runnable in Your Browser
50 Python problems — every one with a working, runnable solution. Click Run on any code block to execute it in your browser. Modify the solution, break it, fix it, extend it. That's how you learn.
The problems are arranged in three tiers: Beginner (1–20) covers fundamentals, Intermediate (21–35) covers algorithms and data structures, and Advanced (36–50) covers performance patterns, dynamic programming, and the data science stack.
Beginner Problems (1–20)
Problem 1: Personalized Greeting
Topic: Strings, f-strings
Write a function greet(name) that returns "Hello, {name}! Welcome to Python.". Test it with several names.
Problem 2: Celsius to Fahrenheit Converter
Topic: Arithmetic, functions
Write celsius_to_fahrenheit(c) using the formula F = C × 9/5 + 32. Test with 0°C (freezing), 100°C (boiling), and -40°C.
Problem 3: Even or Odd
Topic: Modulo operator, conditionals
Write even_or_odd(n) that returns the string "even" or "odd". Handle negative numbers correctly.
Problem 4: FizzBuzz
Topic: Modulo, conditionals, loops
Print numbers 1–30. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", for multiples of both print "FizzBuzz".
Problem 5: Reverse a String
Topic: String slicing
Reverse any string using slice notation. Then test it on a palindrome to confirm it reads the same forwards and backwards.
Problem 6: Count Vowels
Topic: String iteration, conditionals
Count the vowels (a, e, i, o, u) in a string. Case-insensitive.
Problem 7: Palindrome Check
Topic: String manipulation, comparison
Check if a string is a palindrome. Ignore spaces and case.
Problem 8: Sum of a List Without sum()
Topic: Loops, accumulators
Sum a list using a loop — no sum() allowed. Then compare to sum() to verify.
Problem 9: Find Maximum Without max()
Topic: Loops, comparison
Find the largest number in a list without using max(). Handle empty lists gracefully.
Problem 10: Count Words in a Sentence
Topic: Strings, split()
Count words in a sentence. Handle extra whitespace correctly.
Problem 11: Sum of Digits
Topic: Type conversion, iteration
Sum all the digits of an integer. Works for negative numbers too.
Problem 12: Multiplication Table
Topic: Loops, string formatting
Print a formatted multiplication table for any number from 1 to 10.
Problem 13: Check for Duplicates
Topic: Sets
Return True if a list contains any duplicate values. Use the set trick for O(n) performance.
Problem 14: Remove Duplicates (Preserve Order)
Topic: dict.fromkeys(), order preservation
Remove duplicates from a list while keeping the original order. set() doesn't preserve order — use dict.fromkeys() instead.
Problem 15: Simple Interest Calculator
Topic: Arithmetic, functions, f-strings
Calculate simple interest: SI = (principal × rate × time) / 100. Format the output neatly.
Problem 16: Flatten a List (One Level)
Topic: List comprehension, nested loops
Flatten a list of lists into a single list using a comprehension.
Problem 17: Find the Second Largest
Topic: Sets, sorting
Find the second largest unique value in a list.
Problem 18: List Intersection
Topic: Sets
Return elements that appear in both lists. Use set intersection for efficiency.
Problem 19: Transpose a Matrix
Topic: zip(), list comprehension
Transpose a 2D matrix (swap rows and columns) using zip(*matrix).
Problem 20: Character Frequency
Topic: collections.Counter
Count how often each character appears in a string. Show the top 5 most frequent.
Intermediate Problems (21–35)
These problems require combining concepts: recursion, generators, algorithmic thinking, and more complex data structures. Spend 10–15 minutes trying each one before reading the solution.
Problem 21: Fibonacci Generator
Topic: Generators, yield
Create a generator function that yields Fibonacci numbers on demand — memory-efficient for large sequences.
Problem 22: Prime Number Sieve
Topic: Sieve of Eratosthenes, list manipulation
Find all primes up to N using the Sieve of Eratosthenes — more efficient than checking each number individually.
Problem 23: Caesar Cipher
Topic: String manipulation, ord/chr, modular arithmetic
Encode and decode text using a Caesar cipher shift. Preserve case and non-letter characters.
Problem 24: Word Frequency Counter
Topic: collections.Counter, string processing
Count word frequencies in a text, ignoring punctuation and case.
Problem 25: Group Anagrams
Topic: defaultdict, sorting as a key
Group a list of words by their anagram family. Words that are anagrams of each other go in the same group.
Problem 26: Binary Search
Topic: Divide and conquer, O(log n)
Implement binary search from scratch. Returns the index of the target or -1 if not found.
Problem 27: Merge Two Sorted Lists
Topic: Two pointers, merging
Merge two sorted lists into one sorted list in O(n) time, without sorting the result.
Problem 28: Run-Length Encoding
Topic: String parsing, iteration
Compress a string using run-length encoding: "aaabbc" → "a3b2c". Single characters don't get a number.
Problem 29: Valid Brackets
Topic: Stacks
Check if a string of brackets is balanced. Every opening bracket must have a matching closing bracket in the correct order.
Problem 30: Rotate a List
Topic: List slicing, modular arithmetic
Rotate a list left by k positions. Handle k larger than the list length with modulo.
Problem 31: Deep Flatten (Recursive)
Topic: Recursion, isinstance()
Flatten a deeply nested list structure of arbitrary depth.
Problem 32: Sort List of Dicts
Topic: sorted(), lambda, key functions
Sort a list of dictionaries by a specified key. Support both ascending and descending order.
Problem 33: Roman Numeral Converter
Topic: Greedy algorithm, lookup tables
Convert an integer to its Roman numeral representation.
Problem 34: Longest Common Prefix
Topic: String comparison, zip
Find the longest common prefix shared by all strings in a list.
Problem 35: Dictionary from Two Lists
Topic: zip(), dict comprehension
Create a dictionary from two parallel lists: one for keys, one for values. Handle lists of different lengths safely.
Advanced Problems (36–50)
These problems cover performance patterns (decorators, LRU cache, memoization), dynamic programming, graph algorithms, and the data science stack. They represent the level of Python used in professional software engineering and data science roles.
Problem 36: Two Sum
Topic: Hash maps, O(n) solutions
Given a list and a target, return the indices of two numbers that add up to the target. Solve it in O(n) time using a hash map.
Problem 37: Longest Substring Without Repeating Characters
Topic: Sliding window
Find the length of the longest substring without repeating characters.
Problem 38: LRU Cache
Topic: OrderedDict, O(1) get/put
Implement an LRU (Least Recently Used) Cache with get and put operations, both in O(1) time.
Problem 39: Timing Decorator
Topic: Decorators, functools.wraps, time.perf_counter
Write a decorator that measures and prints execution time for any function.
Problem 40: Memoization Decorator
Topic: Decorators, caching, recursion optimization
Build a memoization decorator from scratch. Then use it to make naive recursive Fibonacci fast.
Problem 41: Sliding Window Maximum
Topic: Deque, sliding window, O(n)
Find the maximum value in every window of size k in a list. The naive O(n×k) approach is too slow — use a deque for O(n).
Problem 42: Coin Change (Dynamic Programming)
Topic: Dynamic programming, bottom-up DP
Find the minimum number of coins needed to make an amount. Classic DP problem.
Problem 43: Longest Increasing Subsequence
Topic: Dynamic programming, subsequences
Find the length of the longest strictly increasing subsequence in an array.
Problem 44: Graph BFS — Shortest Path
Topic: BFS, queue, graph traversal
Find the shortest path between two nodes in an unweighted graph using Breadth-First Search.
Problem 45: Trie Data Structure
Topic: Trees, hash maps, prefix searching
Implement a Trie (prefix tree) with insert, search, and starts_with operations. Used in autocomplete systems.
Problem 46: NumPy — Find Statistical Outliers
Topic: NumPy, z-scores, statistical detection
Use NumPy to find outliers in a dataset using z-score normalization.
Problem 47: Pandas — Sales Data Analysis
Topic: Pandas groupby, agg, merge
Analyze a multi-region sales dataset. Find top performers, calculate margins, and identify trends.
Problem 48: Matplotlib — Multi-Chart Dashboard
Topic: Matplotlib subplots, styling
Create a 2×2 dashboard with a line chart, bar chart, histogram, and scatter plot.
Problem 49: Retry Decorator with Exponential Backoff
Topic: Decorators with parameters, exception handling, backoff strategies
Write a @retry decorator that retries a failing function with exponential backoff. Essential for network calls and flaky APIs.
Problem 50: Singleton Pattern via Metaclass
Topic: Metaclasses, design patterns
Implement the Singleton design pattern using a metaclass — so that only one instance of a class can ever exist, no matter how many times it's instantiated.