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 →
- How do you read and write JSON in Python?
Use the json module: json.dumps and json.loads convert between Python objects and JSON strings, while json.dump and json.load do the same with file objects. JSON null becomes None, and keys always become strings.
BeginnerQuick answer1 min read - What are the common file modes in Python's open() function?
r" reads (default), "w" writes and erases existing content, "a" appends to the end, and "x" creates a new file and fails if it exists. Adding "+" allows both read and write, and "b" means binary instead of text.
BeginnerQuick answer1 min read - Why do we use the with statement when working with files?
with guarantees the file is closed when the block ends, even if an exception occurs. It works through a context manager, an object with __enter__ and __exit__ methods, so cleanup does not depend on remembering to call close().
BeginnerQuick answer1 min read