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 →
- Are strings mutable in Python, and how do you change a character in one?
Strings are immutable, so s[0] = "x" raises TypeError. To change one, build a new string using slicing, replace(), or join over a list of characters.
BeginnerQuick answer1 min read - How does string slicing work in Python, and what do negative indices mean?
s[start:stop:step] takes characters from start up to but not including stop. Negative indices count from the end, so s[-1] is the last character. Out-of-range slice bounds are clamped and never raise an error.
BeginnerQuick answer1 min read - What are the different ways to format strings in Python, and which should you prefer?
Python has % formatting, str.format() and f-strings. Prefer f-strings (3.6+): they are the most readable and usually the fastest, because expressions are written directly inside the string.
BeginnerQuick answer1 min read - 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 - What is the difference between str and bytes in Python 3?
str holds Unicode text, a sequence of characters. bytes holds raw 8-bit values. You encode a str to get bytes and decode bytes to get a str, and you must name the encoding, usually UTF-8.
IntermediateQuick answer1 min read - Why is "".join(list_of_strings) preferred over += inside a loop?
Strings are immutable, so each += may copy the whole string built so far, which can become quadratic. join() computes the total size once and copies each piece a single time, so it runs in linear time.
IntermediateQuick answer1 min read