Advertisement

Data Types & Structures interview questions and answers

15 Data Types & Structures interview questions for Python roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How does Python's list implementation achieve amortized O(1) append performance despite lists being dynamically resizable arrays under the hood?

CPython's list over-allocates extra capacity beyond the current size whenever it needs to grow, so most append() calls just write into already-allocated space (O(1)); only occasionally, when capacity is exhausted, does it need to allocate a larger buffer and copy all elements (O(n)) — averaged ('amortized') across many appends, this works out to O(1) per append.
import sys
lst = []
for i in range(10):
    lst.append(i)
    print(len(lst), sys.getsizeof(lst))  # size (in bytes) jumps in chunks, not every single append
Real-world example
Understanding why appending to a Python list in a loop is generally efficient, despite lists being resizable arrays rather than linked lists.
Likely follow-ups
  • How does this over-allocation strategy differ from what happens when you use list.insert(0, x) repeatedly instead of append()?
Memory Management & Garbage Collection
Q12 Advanced Save

How would you implement a custom, memory-efficient data structure using __slots__ instead of a regular class with a __dict__?

Declaring __slots__ = ("attr1", "attr2", ...) on a class tells Python to allocate FIXED, pre-defined storage slots for those specific attributes instead of giving each instance a dynamic __dict__ — significantly reducing per-instance memory overhead, especially valuable when creating MANY instances of a small class.
class Point:
    __slots__ = ("x", "y")  # no per-instance __dict__ allocated
    def __init__(self, x, y):
        self.x = x
        self.y = y
    # point.z = 5  # would raise AttributeError -- no __dict__, no arbitrary new attributes
Real-world example
Reducing memory usage significantly when creating millions of small objects, like Point instances in a large point cloud dataset.
Likely follow-ups
  • What capability do you LOSE by using __slots__, like the ability to add new attributes dynamically?
Descriptors & Properties
Q13 Advanced Save

How do dictionaries maintain insertion order internally since Python 3.7, and what data structure change made this both possible and efficient?

CPython's dict implementation (since 3.6 as an implementation detail, guaranteed by the language spec since 3.7) uses a COMPACT internal representation: a separate, order-preserving array of entries alongside a sparse hash table of INDICES into that array — this achieves both O(1) average hash-based lookup AND stable insertion-order iteration, unlike the older implementation which stored entries directly in hash-table slot order.
d = {}
d["z"] = 1
d["a"] = 2
d["m"] = 3
print(list(d.keys()))  # ['z', 'a', 'm'] -- insertion order preserved, NOT alphabetical or hash order
Real-world example
Relying on dict insertion order being preserved for building an ordered configuration or an ordered API response body.
Likely follow-ups
  • Before Python 3.7, what dedicated class from the collections module was needed to guarantee this same ordering behavior?
Standard Library Essentials (collections itertools)
Q14 Advanced Save

How would you use collections.Counter to efficiently count occurrences and find the most common elements in a large dataset?

Counter is a dict subclass specialized for counting hashable items — pass it any iterable to get automatic frequency counts, and use .most_common(n) to efficiently retrieve the top N most frequent elements without writing manual counting logic.
from collections import Counter

words = "the quick brown fox jumps over the lazy dog the fox runs".split()
counts = Counter(words)
print(counts["the"])          # 3
print(counts.most_common(2))   # [('the', 3), ('fox', 2)]
Real-world example
Analyzing word frequency in a large text corpus, or finding the most common error codes in a log file.
Likely follow-ups
  • How does Counter support arithmetic operations like addition and subtraction between two Counter objects?
Standard Library Essentials (collections itertools)
Q15 Advanced Save

How would you choose between a list, a set, a dict, and a specialized structure like heapq for efficiently finding the K smallest/largest elements in a large dataset?

heapq.nsmallest(k, iterable) or heapq.nlargest(k, iterable) is generally the most efficient choice for finding just K elements from a large dataset (O(n log k) rather than sorting the ENTIRE dataset at O(n log n) with sorted()[:k]) — a plain sort is simpler and fine for small datasets, but heapq scales much better when the dataset is large and K is small relative to it.
import heapq

scores = [45, 92, 78, 12, 88, 67, 99, 34]
top_3 = heapq.nlargest(3, scores)
print(top_3)  # [99, 92, 88] -- more efficient than sorted(scores, reverse=True)[:3] for large datasets
Real-world example
Finding the top 10 highest-scoring results from a dataset of millions of records without fully sorting the entire dataset.
Likely follow-ups
  • At roughly what ratio of K to total dataset size does heapq's efficiency advantage over a full sort become negligible?
Debugging & Profiling

Showing 11–15 of 15