Q.Can we pass a tuple of numbers as an argument to writelines()? Will it be written to the file or an error will be generated?
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →writelines() expects an iterable of strings, not numbers. Passing a tuple of numbers will cause a TypeError because the method tries to concatenate non-string objects.
The question tests your understanding of Python's file-writing methods — specifically, what writelines() actually expects as input. Many students confuse it with write(), which can take a single string, and assume writelines() will accept any iterable and convert elements automatically. That is not how it works.
writelines() is a method of file objects in Python. Its signature is:
file_object.writelines(iterable)
The method takes an iterable (list, tuple, set, generator, etc.) and writes each element to the file one after another, without adding any separators (no newlines, no commas). But here is the critical constraint: every element in the iterable must be a string. If any element is not a string, Python raises a TypeError.
So when you pass a tuple of numbers — say (10, 20, 30) — Python sees three integers. It tries to write the first integer, fails because write() expects a string, and raises:
TypeError: write() argument must be str, not int
A common mistake is to think writelines() will automatically convert numbers to strings. It does not. You must explicitly convert each element to a string — for example, using map(str, tuple_of_numbers) or a list comprehension.
Let's see this in action:
# This will raise an error
with open("test.txt", "w") as f: …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.