Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/Implement a Python function to count unique words from a file and write them to another file.

Implement a Python function to count unique words from a file and write them to another file.

Python/Codinghard2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

To count unique words from a file and write them to another, use a Python set for efficient deduplication and standard file I/O. Mechanics and Why The core idea is to read the input file line by line,…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
American Express
Key Concepts Tested
joinpython

Why This Question Matters

This hard-level Python/Coding question appears frequently in data engineering interviews at companies like American Express. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (join, python) will help you answer variations of this question confidently.

How to Approach This

This is a senior-level question that tests architectural thinking. Lead with the high-level design, then drill into specifics. Discuss trade-offs explicitly - there is rarely one correct answer. Show awareness of scale, fault tolerance, and operational complexity. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
354 wordsIncludes code

To count unique words from a file and write them to another, use a Python set for efficient deduplication and standard file I/O.

Mechanics and Why

The core idea is to read the input file line by line, split each line into words, and add these words to a set. A set automatically handles uniqueness, as it can only contain distinct elements, offering average O(1) time complexity for additions. After processing all lines, the set will contain every unique word. These can then be sorted and written to the output file, each on a new line. While collections.Counter can count word frequencies, set is more direct for simply identifying unique words.

Production Considerations and Trade-offs

For production-grade solutions, several aspects need attention: * Encoding: Always specify encoding='utf-8' (or the correct encoding) when opening files to prevent UnicodeDecodeError with non-ASCII characters. * Tokenization: The default str.split() handles whitespace. For more robust word extraction, consider: * Case-insensitivity: Convert words to lowercase (word.lower()) before adding to the set. * Punctuation: Remove leading/trailing punctuation using word.strip(string.punctuation) or regular expressions (re.sub(r'[^\w\s]', '', word)). * Large Files: For files exceeding available memory, the current approach of loading all unique words into a single set might fail. * Memory Efficiency: Ensure you're processing line-by-line using file iterators. * Distributed Processing: In big data environments, this task would be distributed. Frameworks like Apache Spark could read the file in partitions, map each word to a key, and then use a distinct or groupByKey followed by count operation to get unique words across the cluster, handling shuffling and memory management. * External Sorting: If the final sorted list of unique words is too large to fit in memory, an external sort algorithm would be required.
import string

def count_unique_words(input_filepath: str, output_filepath: str):
unique_words = set()
with open(input_filepath, 'r', encoding='utf-8') as infile:
for line in infile:
for word in line.lower().split(): # Case-insensitive tokenization
cleaned_word = word.strip(string.punctuation)
if cleaned_word: # Avoid adding empty strings after cleaning
unique_words.add(cleaned_word)

with open(output_filepath, 'w', encoding='utf-8') as outfile:
outfile.write('\n'.join(sorted(unique_words)))

In the interview, also mention asking clarifying questions about case sensitivity, punctuation handling, and expected file size.

⚡
Pro Tip

Pro-Move: Streaming for large files. Red Flag: Loading full file.

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer