Interview Q&A / Python
Python interview questions
Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.
Prefer rapid revision? Practise Python short interview answers →
- Write a function that reverses a string in Python.
The shortest way is slicing with a negative step: s[::-1]. You can also use "".join(reversed(s)). Both build a new string in O(n) time, since strings cannot be changed in place.
BeginnerQuick answerCoding1 min read - Write a function to check whether a string is a palindrome, ignoring case and non-letters.
Clean the string by keeping only letters and digits in lowercase, then compare it with its reverse. This runs in O(n) time. A two-pointer version avoids the extra reversed copy.
BeginnerQuick answerCoding1 min read - Write a function to check whether two strings are anagrams of each other.
Two strings are anagrams if they contain the same characters with the same counts. Compare Counter(a) with Counter(b) in O(n) time, or compare sorted(a) with sorted(b) in O(n log n) time.
BeginnerQuick answerCoding1 min read - Write a function to flatten a list of lists into a single list.
For one level of nesting, use a nested comprehension: [x for row in rows for x in row]. For arbitrary depth, use recursion and check isinstance(item, list). The flat version is O(n) in the number of elements.
BeginnerQuick answerCoding1 min read - Write a function to remove duplicates from a list while keeping the original order.
Walk through the list, keep a set of items already seen, and add an item to the result only if it is not in the set. This is O(n) time. Using set(lst) alone is fast but loses the order.
BeginnerQuick answerCoding1 min read - Write a generator that yields the first n Fibonacci numbers.
Keep two variables a and b, yield a, then update them with a, b = b, a + b, repeating n times. The generator produces one value at a time, uses O(1) memory and does O(n) additions in total.
BeginnerQuick answerCoding1 min read