POC Data Structures & File Handling 3 — Questions and Answers
Question 1: What is the output of `sorted({'b': 2, 'a': 1, 'c': 3})`?
- ['a', 'b', 'c'] (Correct answer)
- [1, 2, 3]
- {'a': 1, 'b': 2, 'c': 3}
- [('a',1),('b',2),('c',3)]
Correct answer: ['a', 'b', 'c']
`sorted()` on a dictionary iterates over its keys and returns them in sorted order as a list.
Question 2: Which data structure should you use to count the frequency of each word in a text efficiently?
- collections.Counter (Correct answer)
- list
- tuple
- set
Correct answer: collections.Counter
`collections.Counter` is a dict subclass designed to count hashable objects, making it ideal for frequency analysis.
Question 3: What exception is raised when you try to read from a file opened in write-only mode (`'w'`)?
- UnsupportedOperation (Correct answer)
- PermissionError
- ValueError
- IOError
Correct answer: UnsupportedOperation
`io.UnsupportedOperation` (a subclass of `OSError`) is raised when an unsupported operation like reading is attempted on a write-only file.
Question 4: What does `list.extend([4, 5])` do compared to `list.append([4, 5])`?
- extend adds each element individually; append adds the list as a single element (Correct answer)
- Both behave identically
- extend is slower than append
- append adds each element; extend adds as one element
Correct answer: extend adds each element individually; append adds the list as a single element
`extend()` unpacks the iterable and adds each item, while `append()` inserts the whole object as a single new element.
Question 5: What is the output of `tuple([1, 2, 3]) == (1, 2, 3)`?
- True (Correct answer)
- False
- TypeError
- None
Correct answer: True
`tuple([1, 2, 3])` constructs the tuple `(1, 2, 3)`, which compares equal to the literal `(1, 2, 3)`.
Question 6: Which `os` module function returns the current position of the file pointer?
- f.tell() (Correct answer)
- f.seek(0)
- os.position(f)
- f.pos()
Correct answer: f.tell()
`f.tell()` returns the current byte offset of the file pointer from the beginning of the file.
Question 7: In a Python dict, what happens when you assign a value to an existing key?
- The value is overwritten (Correct answer)
- A duplicate key is created
- A ValueError is raised
- The old value is appended to a list
Correct answer: The value is overwritten
Dictionaries enforce unique keys; assigning to an existing key replaces its value in-place.
What is the output of `sorted({'b': 2, 'a': 1, 'c': 3})`?