
30 Python Coding Questions and Answers to Know
If you're screening candidates for a Python developer role, you need a reliable set of python coding questions ready before the interview starts. Guessing what to ask, or pulling random questions off forums, wastes your time and the candidate's. You end up with a session that tells you nothing about whether the person can actually write working code under pressure.
This article gives you exactly that: 30 python coding questions and answers covering basics, intermediate logic, and a few trickier problems that separate strong candidates from average ones, and it pairs well with our list of Python programmer interview questions. Each question comes with a clear solution so you can evaluate answers quickly, whether you're conducting the interview yourself or briefing a hiring manager on the Python questions hiring managers ask most.
You'll find questions suited for freshers as well as ones aimed at more experienced applicants, so you can adjust the difficulty based on the role you're hiring for. If you're managing a high volume of technical interviews, pairing a question bank like this with AI-powered screening tools can cut hours off your process, something we cover briefly toward the end.
1. Basic Python coding questions everyone should know
Every interview should open with basic python coding questions that confirm a candidate can handle syntax without hesitation. These aren't meant to be hard. They're meant to filter out people who padded their resume with Python but can't write a loop from memory. If someone stumbles here, you've saved yourself 40 minutes of a longer interview that was never going anywhere.

Sample questions to practice
Use these as your opening round for python coding questions for beginners or freshers with under two years of experience, alongside these beginner Python interview questions and answers:
- Write a function that checks if a number is prime.
- Reverse a string without using slicing.
- Find the factorial of a number using a loop and using recursion.
- Swap two variables without a temporary variable.
- Check if a given year is a leap year.
Step-by-step solutions
Here's a clean solution to the prime-number check, one of the most common basic coding questions in python:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
Walk the candidate through why the loop stops at the square root of n rather than running all the way to n. A candidate who explains that shortcut unprompted is already thinking about efficiency, not just correctness.
For the leap year check, look for this logic instead of a hardcoded list of years:
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
A candidate who can explain their code, not just produce it, is worth more than one who memorized the syntax.
What interviewers are testing
At this stage you're not evaluating cleverness, you're evaluating fundamentals. Can the candidate write a function signature correctly? Do they know the difference between range() behavior and off-by-one errors? Do they default to brute force when a simple optimization is available? These basic python coding questions and answers also reveal communication style: does the candidate narrate their thinking, or do they go silent and just type? For remote screening rounds, that narration matters as much as the final output, since it predicts how they'll behave in code reviews and pair programming later, which is why running structured remote interviews with a scoring plan pays off. If you're running these questions through Olibr's automated AI interview screening, the scored transcripts flag exactly this kind of reasoning gap automatically.
2. String manipulation coding questions
Strings show up in almost every real coding task, from parsing resumes to cleaning up log files, so string manipulation coding questions are a natural second round. They also expose candidates who rely on built-in methods without understanding what happens underneath, which matters if you ever need them to debug a performance issue in production.
Sample questions to practice
These work well as python coding questions for practice once the basics round is cleared:
- Check if a string is a palindrome.
- Count the frequency of each character in a string.
- Find the first non-repeating character in a string.
- Check if two strings are anagrams of each other.
- Remove all duplicate characters from a string while preserving order.
Step-by-step solutions
Here's a solid answer to the anagram check, one of the more common coding questions in python for this category:
def is_anagram(a, b):
return sorted(a) == sorted(b)
Ask the candidate for a version that avoids sorting, since sorting costs O(n log n) when a character-count approach runs in O(n):
from collections import Counter
def is_anagram_fast(a, b):
return Counter(a) == Counter(b)
The candidate who offers a faster alternative without being asked is showing you how they'll actually work on your team.
What interviewers are testing
Here you're checking whether the candidate understands string immutability in Python and why repeated concatenation in a loop is a bad habit. Watch for whether they reach for Counter, set(), or dictionary counting naturally, since that signals real project experience rather than textbook memorization. These questions and answers also reveal how comfortable someone is trading a readable one-liner for a more efficient approach when the interview pushes them on performance.
3. List and array coding questions
Lists are where most Python candidates spend their daily work, so list and array coding questions tell you a lot about how someone handles real data manipulation tasks. Weak candidates default to nested loops for everything. Strong ones reach for list comprehensions, slicing, or built-in functions like zip() and enumerate() when they fit better.
Sample questions to practice
These are reliable python coding questions for practice once you've moved past strings:
- Find the second largest number in a list without sorting.
- Remove duplicates from a list while preserving order.
- Find the intersection of two lists.
- Rotate a list by k positions.
- Flatten a nested list of arbitrary depth.
Step-by-step solutions
Here's a clean answer to the second-largest-number problem, a favorite among python intermediate coding questions:
def second_largest(nums):
first = second = float('-inf')
for n in nums:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second
Ask why this beats sorting the list first. The answer: sorting costs O(n log n), while this single pass runs in O(n).
A candidate who avoids sorting when a single pass will do already understands complexity, not just syntax.
For rotating a list, check whether they use slicing cleanly:
def rotate(lst, k):
k %= len(lst)
return lst[-k:] + lst[:k]
What interviewers are testing
This round tests whether a candidate thinks about time complexity before writing code, or just gets something working and stops there. Watch how they handle edge cases like empty lists, single-element lists, or a rotation value larger than the list length. Their instinct to reach for comprehensions over manual loops also tells you how much idiomatic Python they've actually written on the job, versus how much they've only read about.
4. Dictionary and set coding questions
Dictionaries and sets separate candidates who understand Python's data structures from those who just use lists for everything. Dictionary and set coding questions reveal whether someone knows when O(1) lookups actually matter, and whether they reach for a hash-based structure instead of scanning a list every time they need a fast membership check.
Sample questions to practice
These questions work well as python coding questions with solutions once a candidate has cleared lists and strings:
- Find duplicate elements in a list using a set.
- Count word frequency in a sentence using a dictionary.
- Merge two dictionaries and handle overlapping keys.
- Find the union and intersection of two sets.
- Group a list of words by their first letter using a dictionary.
Step-by-step solutions
Here's a clean answer to the word-frequency problem, a common entry among python coding questions for freshers:
def word_frequency(sentence):
freq = {}
for word in sentence.lower().split():
freq[word] = freq.get(word, 0) + 1
return freq
Ask the candidate to rewrite this with collections.Counter to see if they know the shortcut:
from collections import Counter
def word_frequency_fast(sentence):
return Counter(sentence.lower().split())
Knowing when a hash lookup beats a loop is the difference between code that works and code that scales.
For merging dictionaries, check whether they know the | operator introduced in Python 3.9, not just the older update() method.
What interviewers are testing
This round checks whether a candidate understands hashability and why sets can't hold mutable items like lists. Watch how they handle duplicate keys during a merge, since that decision reveals attention to edge cases. Their choice between manual loops and built-in tools like Counter or defaultdict also tells you how much production code they've actually shipped, and these essential Python tips and tricks for programmers cover the shortcuts strong candidates already use.
5. Tuple and basic data structure questions
Tuples get overlooked in interview prep, but tuple and basic data structure questions show you whether a candidate understands immutability and when to choose a tuple over a list. Candidates who default to lists for everything, even data that should never change, haven't thought carefully about why Python gives you multiple structures in the first place. This round is short, but it's a good filter for people who treat data structures as interchangeable rather than purposeful.
Sample questions to practice
These work well as python basic coding questions once you've covered lists, dicts, and sets:
- Explain the difference between a tuple and a list, then show when you'd use each.
- Swap two values using tuple unpacking.
- Convert a list of tuples into a dictionary.
- Find the maximum value in a list of tuples based on the second element.
- Check if a tuple contains a nested mutable object.
Step-by-step solutions
Here's a clean answer to sorting tuples by a specific field, a common ask among basic python coding questions:
data = [("apple", 3), ("banana", 1), ("cherry", 2)]
sorted_data = sorted(data, key=lambda x: x[1])
Ask the candidate to explain what key=lambda x: x[1] does before they run it. If they can't articulate it, they likely copied the pattern without understanding it.
A candidate who picks a tuple over a list on purpose already understands more about Python than one who can recite syntax.
What interviewers are testing
This section checks whether someone grasps immutability and why it matters for things like dictionary keys or function arguments that shouldn't change. Watch for whether they mention hashability unprompted when explaining why tuples work as dict keys and lists don't. That single detail tells you they've actually debugged a TypeError in production, not just read about tuples in a tutorial.
6. Searching and sorting algorithm questions
Once a candidate clears data structures, searching and sorting algorithm questions tell you whether they understand what happens under the hood instead of just calling .sort() and moving on. This round matters most for roles that touch large datasets, since a candidate who picks the wrong algorithm for the wrong input size will eventually cost you real infrastructure money.

Sample questions to practice
These questions work well as python coding questions for practice once a candidate has shown they know lists and dictionaries:
- Implement binary search on a sorted list.
- Sort a list without using the built-in
sort()function. - Find the kth largest element in an unsorted list.
- Implement bubble sort and explain its time complexity.
- Search for a target value in a rotated sorted array.
Step-by-step solutions
Here's a clean binary search implementation, one of the most requested python coding questions with answers in this category:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Ask the candidate why this runs in O(log n) instead of O(n), and whether it works on an unsorted list. Most candidates say no immediately; the ones worth hiring explain why the halving logic depends entirely on sorted order.
A candidate who can name the time complexity of their own code, unprompted, is already thinking like an engineer.
What interviewers are testing
This round checks whether someone understands algorithmic complexity well enough to choose the right tool for a dataset of 100 rows versus one with 10 million. Watch whether they default to brute force or recognize when a sorted structure enables a faster search. Their explanation of trade-offs here often predicts how they'll handle performance reviews on your actual codebase.
7. Recursion and mathematical logic questions
Recursion trips up more candidates than any other topic on this list, which makes recursion and mathematical logic questions one of the sharpest filters you have. A candidate who understands recursion tends to understand call stacks, base cases, and why a missing exit condition crashes a program. Someone who's only memorized loops usually freezes here, and that hesitation tells you plenty about how they'll handle unfamiliar problems on the job.
Sample questions to practice
These work well as python intermediate coding questions once basics and data structures are covered, and they sit alongside our broader set of intermediate-level Python questions:
- Calculate the Fibonacci sequence using recursion, then optimize it with memoization.
- Find the greatest common divisor of two numbers.
- Check if a number is a palindrome without converting it to a string.
- Write a recursive function to calculate the sum of digits.
- Solve the Tower of Hanoi problem and explain the recursive pattern.
Step-by-step solutions
Here's a memoized Fibonacci solution, a staple among python coding questions and answers for this round:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
Ask why plain recursion without lru_cache runs in exponential time. Strong candidates explain that overlapping subproblems get recalculated repeatedly without caching.
A candidate who spots redundant recursive calls before you point them out already thinks in terms of efficiency, not just output.
What interviewers are testing
This round checks whether someone grasps base cases and stack depth limits, not just the general idea of a function calling itself. Watch whether they mention Python's recursion limit or suggest an iterative rewrite for deep inputs. That awareness separates candidates who've hit a RecursionError in production from those who've only seen recursion in a classroom.
8. Object-oriented programming questions
Most production Python code lives inside classes, so object-oriented programming questions tell you whether a candidate can structure real applications instead of writing everything as standalone functions. This round matters especially for backend or platform roles, where inheritance, encapsulation, and clean interfaces determine how maintainable the codebase stays as your team grows.

Sample questions to practice
These questions work well as python coding questions with solutions once a candidate has cleared functional topics, and you can extend the round with general object-oriented programming interview questions:
- Design a class hierarchy for different types of employees using inheritance.
- Explain the difference between class methods, static methods, and instance methods.
- Implement a simple bank account class with deposit and withdrawal methods that prevent overdrafts.
- Override the
__str__and__eq__methods for a custom class. - Explain polymorphism using a real example from a project you've built.
Step-by-step solutions
Here's a clean answer to the bank account problem, a frequent entry among python coding questions and answers for this category:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Insufficient funds")
self.balance -= amount
return self.balance
Ask why raising an exception beats silently returning False. Strong candidates explain that exceptions surface bugs immediately instead of letting bad states slide through unnoticed.
A candidate who defends a class design choice with a reason, not a guess, understands architecture, not just syntax.
What interviewers are testing
This round checks whether someone understands encapsulation and why exposing internal state directly invites bugs down the line. Watch whether they reach for inheritance appropriately, or force it onto problems that a simple function would solve better. Their comfort with dunder methods often reveals how much real object-oriented code they've shipped versus studied.
9. File handling coding questions
File handling rarely shows up in tutorials, but production code reads config files, parses CSVs, and writes logs constantly, so file handling coding questions reveal whether a candidate has actually built something that survives outside a Jupyter notebook. Candidates who've only worked with in-memory data often stumble the moment you ask them to open, read, and safely close a file without leaking a handle.
Sample questions to practice
These questions work well as python coding questions for practice once a candidate has covered data structures and OOP:
- Read a text file and count the number of lines, words, and characters.
- Write a function that appends a log entry with a timestamp to a file.
- Read a CSV file and convert each row into a dictionary.
- Find and remove duplicate lines from a text file.
- Handle a missing file gracefully without crashing the program.
Step-by-step solutions
Here's a clean answer to the missing-file problem, a common ask among python coding questions with answers:
def read_file_safe(path):
try:
with open(path, "r") as f:
return f.read()
except FileNotFoundError:
return ""
Ask why the candidate used with instead of calling open() and close() manually. The right answer: with guarantees the file closes even if an exception interrupts the read.
A candidate who reaches for
withautomatically has already been burned by a file handle left open in production.
What interviewers are testing
This round checks whether someone understands context managers and defensive error handling, not just the mechanics of reading a file. Watch whether they catch specific exceptions like FileNotFoundError instead of a bare except, since that habit predicts how they'll handle failures in your actual pipelines.
10. Intermediate and advanced coding questions
By the final round, you want intermediate and advanced coding questions that mix two or three concepts at once, since real production bugs rarely involve just one data structure or one algorithm in isolation. These questions separate candidates who can combine skills under pressure from those who only perform well when a problem is presented in isolation, one topic at a time.
Sample questions to practice
Use these as closing top 100 python coding questions-style challenges for senior or mid-level candidates, supplemented by advanced Python questions for senior developers:
- Detect a cycle in a linked list.
- Implement an LRU cache from scratch.
- Find the longest substring without repeating characters.
- Merge overlapping intervals from a list of ranges.
- Design a rate limiter using a queue or sliding window.
Step-by-step solutions
Here's a clean answer to the longest-substring problem, a frequent pick among python coding questions and answers for senior interviews:
def longest_unique_substring(s):
seen = {}
start = max_len = 0
for i, ch in enumerate(s):
if ch in seen and seen[ch] >= start:
start = seen[ch] + 1
seen[ch] = i
max_len = max(max_len, i - start + 1)
return max_len
Ask why this sliding-window approach beats a nested-loop brute force. The answer: it runs in O(n) instead of O(n squared), since each character gets visited once.
A candidate who reaches for a sliding window instead of nested loops has already solved this problem before, somewhere real.
What interviewers are testing
This round checks whether a candidate can blend data structures and algorithms under time pressure, not just recall isolated patterns. Watch whether they talk through trade-offs before coding, since that habit predicts how they'll handle ambiguous tickets on your actual team.
Turning practice into interview-ready skills
Thirty questions won't make anyone a Python expert, but they will tell you, within one session, whether a candidate can write working code and explain their reasoning. That's the real goal here: not testing memorized syntax, but watching how someone thinks through a prime-number check or a sliding-window problem when you push back with a follow-up question. Use this list as a starting bank, then swap in variations once candidates start recognizing the patterns from other interviews.
Running dozens of these sessions manually gets expensive fast, especially if you're screening at volume. That's where AI-powered screening earns its keep, scoring transcripts and flagging reasoning gaps before a human interviewer ever joins the call. If you're hiring Python developers regularly, browse verified Python developer profiles on Olibr and skip straight to the ones who've already cleared technical vetting.
For engineers
Find work worth your time.
Live engineering roles across India and the US, matched to your stack. Build a profile recruiters actually discover.