POC Data Structures & File Handling 2 — Questions and Answers
Question 1: What does the `collections.deque` class offer that a regular list does not?
- O(1) append and pop from both ends (Correct answer)
- Automatic sorting of elements
- Built-in JSON serialization
- Thread-safe iteration
Correct answer: O(1) append and pop from both ends
`deque` provides O(1) time complexity for appending and popping from both the left and right ends, while list pop(0) is O(n).
Question 2: Which file mode string opens a binary file for both reading and writing without truncating it?
- rb+ (Correct answer)
- wb
- ab+
- xb
Correct answer: rb+
`rb+` opens a binary file for both reading and writing, preserving existing content, while `wb` truncates the file.
Question 3: Given `d = {'a': 1, 'b': 2}`, what does `d.get('c', 0)` return?
- 0 (Correct answer)
- None
- KeyError
- False
Correct answer: 0
`dict.get(key, default)` returns the default value (0 here) when the key is not found, instead of raising KeyError.
Question 4: What is the result of `[1, 2, 3] + [4, 5]` in Python?
- [1, 2, 3, 4, 5] (Correct answer)
- [5, 7, 3]
- TypeError
- [1, 2, 3, [4, 5]]
Correct answer: [1, 2, 3, 4, 5]
The `+` operator on lists performs concatenation, returning a new list with all elements from both lists.
Question 5: When using `with open('file.txt') as f:`, what happens to the file when the block exits?
- It is automatically closed (Correct answer)
- It is deleted
- It is flushed but remains open
- Nothing happens
Correct answer: It is automatically closed
The context manager protocol calls `f.__exit__()`, which closes the file automatically even if an exception occurs.
Question 6: What does `set.discard(x)` do differently from `set.remove(x)`?
- It does not raise an error if x is not present (Correct answer)
- It removes all occurrences of x
- It returns the removed element
- It clears the entire set
Correct answer: It does not raise an error if x is not present
`discard()` silently ignores missing elements, while `remove()` raises a `KeyError` if the element is not found.
Question 7: Which method reads all lines of a text file into a list of strings?
- readlines() (Correct answer)
- read()
- readline()
- fetchlines()
Correct answer: readlines()
`readlines()` reads the entire file and returns each line as a string element in a list, including newline characters.
What does the `collections.deque` class offer that a regular list does not?