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 →
- What is the difference between __str__ and __repr__ in Python?
__str__ gives a readable description meant for users and is used by print() and str(). __repr__ gives an unambiguous description meant for developers, ideally looking like code that recreates the object. If only __repr__ exists, print falls back to it.
BeginnerQuick answer1 min read - How do you make your own class work with +, len() and indexing in Python?
Implement the matching dunder methods: __add__ for +, __len__ for len(), and __getitem__ for obj[i]. Python translates the syntax into calls to these methods, so no inheritance from built-in types is needed.
IntermediateQuick answer1 min read - Why must you define __hash__ when you define __eq__ for objects used in sets or as dict keys?
Objects that compare equal must have the same hash, or sets and dicts will treat them as different. Defining __eq__ without __hash__ sets __hash__ to None, so the class becomes unhashable. Base the hash on the same fields that __eq__ compares.
AdvancedQuick answer1 min read