Python Interview Questions
In this page:
Reversing Collections
Reversing a string or list is a near-universal warm-up interview question, and Python's slice notation makes it trivial: s[::-1] reverses any sequence in one expression by stepping backward through it, without needing an explicit loop or a separate reversal function.
Example: Reversing Collections
text = "hello"
print(text[::-1])
Anagram and Palindrome Verification
Palindrome checks (does a string read the same forwards and backwards?) and anagram checks (do two strings contain exactly the same letters, just rearranged?) are common follow-ups that test whether you reach for the right built-in tool -- slicing for palindromes, sorted() or Counter for anagrams -- rather than hand-rolling character-counting logic.
Example: Anagram and Palindrome Verification
def is_palindrome(s):
return s == s[::-1]
def is_anagram(a, b):
return sorted(a) == sorted(b)
print(is_palindrome("level"))
print(is_anagram("listen", "silent"))
Counting Character Frequencies
Counting how often each character appears in a string is most cleanly solved with a dictionary (or collections.Counter, which does the same thing with less code), mapping each character to a running count as you iterate through the string once.
Example: Counting Character Frequencies
from collections import Counter
text = "banana"
print(Counter(text))
List Comprehensions vs map()
Interviewers often ask you to translate between list comprehensions and equivalent map()/filter() calls, since both express the same 'transform each element' or 'keep only matching elements' idea -- being fluent in both shows you understand the underlying pattern, not just one particular syntax for it.
Example: List Comprehensions vs map()
nums = [1, 2, 3]
squares_comp = [x * x for x in nums]
squares_map = list(map(lambda x: x * x, nums))
print(squares_comp == squares_map)
Finding Duplicates with Sets
Finding duplicates in a list efficiently means avoiding the naive O(n²) nested-loop comparison and instead using a set to track values already seen, giving average O(n) time since set membership checks are O(1) -- a textbook example of trading a bit of extra memory for a large speed improvement.
Example: Finding Duplicates with Sets
def find_duplicates(items):
seen = set()
duplicates = set()
for item in items:
if item in seen:
duplicates.add(item)
seen.add(item)
return duplicates
print(find_duplicates([1, 2, 3, 2, 4, 1]))
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects