Python is the most popular language used in coding interviews today. Many candidates choose it even if it's not their primary language at work—and for good reason. Python is expressive, concise, and easy to learn. However, a common pitfall is that candidates code in Python but think in other languages, failing to leverage the full potential of idiomatic Python.
Below I have gathered the top mistakes non-Pythonist candidates make when writing code during interviews, along with how to improve them.
1. Inefficient Looping Over Indices Instead of Elements
How People Write It:
nums = [1, 2, 3, 4, 5]
for i in range(len(nums)):
print(nums[i])
How It Can Be Better Written:
nums = [1, 2, 3, 4, 5]
for num in nums:
print(num)
Explanation:
Issue: Using
range(len(nums))
to iterate over list indices is unnecessary and less readable.Improvement: Directly iterate over the elements using
for num in nums
, which is more Pythonic and efficient.
2. Manually Managing Loop Indices When Enumerate Exists
How People Write It:
words = ["apple", "banana", "cherry"]
index = 0
for word in words:
print(f"{index}: {word}")
index += 1
How It Can Be Better Written:
words = ["apple", "banana", "cherry"]
for index, word in enumerate(words):
print(f"{index}: {word}")
Explanation:
Issue: Manually incrementing an index variable is error-prone and verbose.
Improvement: Use
enumerate()
to get both the index and the element in each iteration.
3. Using Traditional Swapping Instead of Tuple Unpacking
How People Write It:
temp = a
a = b
b = temp
How It Can Be Better Written:
a, b = b, a
Explanation:
Issue: The traditional method requires an extra variable and more lines of code.
Improvement: Python's tuple unpacking allows swapping variables in a single, clear statement.
4. Not Utilizing defaultdict
for Counting
How People Write It:
counts = {}
for item in items:
if item in counts:
counts[item] += 1
else:
counts[item] = 1
How It Can Be Better Written:
from collections import defaultdict
counts = defaultdict(int)
for item in items:
counts[item] += 1
Explanation:
Issue: Manually checking for key existence leads to verbose code.
Improvement: Use
defaultdict(int)
to automatically initialize counts to zero.
5. Not Utilizing Counter
from collections
for Counting Elements
How People Write It:
def is_anagram(s, t):
if len(s) != len(t):
return False
count_s = {}
count_t = {}
for c in s:
count_s[c] = count_s.get(c, 0) + 1
for c in t:
count_t[c] = count_t.get(c, 0) + 1
return count_s == count_t
How It Can Be Better Written:
from collections import Counter
def is_anagram(s, t):
return Counter(s) == Counter(t)
Explanation:
Issue: Manually counting elements is verbose and error-prone.
Improvement: Use
Counter
to efficiently count elements and compare.
6. Not Using List Comprehensions for Simple Transformations
How People Write It:
squares = []
for num in nums:
squares.append(num * num)
How It Can Be Better Written:
squares = [num * num for num in nums]
Explanation:
Issue: Using loops for simple list transformations is less concise.
Improvement: List comprehensions provide a readable and efficient way to create lists.
7. Not Using zip
to Iterate Over Multiple Sequences
How People Write It:
for i in range(len(list1)):
print(list1[i], list2[i])
How It Can Be Better Written:
for item1, item2 in zip(list1, list2):
print(item1, item2)
Explanation:
Issue: Using indices to access elements from multiple lists is less readable.
Improvement: Use
zip()
to iterate over multiple sequences in parallel.
8. Not Using any()
or all()
for Checking Conditions
How People Write It:
def has_positive(nums):
for num in nums:
if num > 0:
return True
return False
How It Can Be Better Written:
def has_positive(nums):
return any(num > 0 for num in nums)
Explanation:
Issue: Writing loops for simple condition checks adds unnecessary code.
Improvement: Use
any()
to check if any element meets a condition.
9. Re-Implementing sum()
, max()
, or min()
Instead of Using Built-in Functions
How People Write It:
def find_sum(nums):
total = 0
for num in nums:
total += num
return total
How It Can Be Better Written:
def find_sum(nums):
return sum(nums)
Explanation:
Issue: Manually calculating sums or finding maximum/minimum values is unnecessary.
Improvement: Use built-in functions like
sum()
,max()
, andmin()
for clarity and efficiency.
10. Not Using set
Operations for Common Set Logic (Intersection, Union, Difference)
How People Write It:
def common_elements(list1, list2):
result = []
for item in list1:
if item in list2:
result.append(item)
return result
How It Can Be Better Written:
def common_elements(list1, list2):
return list(set(list1) & set(list2))
Explanation:
Issue: Manually checking for common elements is less efficient.
Improvement: Use set operations like intersection (
&
), union (|
), and difference (-
) for cleaner and faster code.
11. Not Using Dictionary's get()
Method with Default Values
How People Write It:
if key in my_dict:
value = my_dict[key]
else:
value = default_value
How It Can Be Better Written:
value = my_dict.get(key, default_value)
Explanation:
Issue: Manually checking for key existence adds extra code.
Improvement: Use
dict.get()
to simplify dictionary lookups with default values.
12. Not Using Slicing for Reversing Strings or Lists
How People Write It:
def reverse_string(s):
reversed_s = ''
for char in s:
reversed_s = char + reversed_s
return reversed_s
How It Can Be Better Written:
def reverse_string(s):
return s[::-1]
Explanation:
Issue: Building a new string character by character is inefficient.
Improvement: Use slicing with
[::-1]
to reverse strings or lists efficiently.
Final Thoughts
Embracing Pythonic idioms not only makes your code more elegant but also demonstrates a deeper understanding of the language during interviews. Here's how to incorporate these practices:
Practice writing code: Solve problems using Python to internalize these idioms.
Review standard library: Explore modules like
collections
,itertools
, and built-in functions.Read others' code: Look at well-written Python code to see these idioms in action.
Stay curious and happy coding!
Nurbo
Need Help with Coding Interviews?
If you need one-on-one help with your tech interview preparation (coding, system design or behavioral) I can probably help you. Book a free introductory session with me here: https://link.faangshui.com/book.