grok-3-mini-beta· xAI
LMArena Human Preference 140K
write a python function that takes a list of emails and returns a deduplicated…
- User
write a python function that takes a list of emails and returns a deduplicated normalized list
- Assistant
Here's a Python function that takes a list of email strings, normalizes them (by converting to lowercase and stripping leading/trailing whitespace), and returns a deduplicated list. The function preserves the order of first occurrences.
def deduplicate_and_normalize(emails): """ Takes a list of email strings, normalizes them (converts to lowercase and strips whitespace), and returns a deduplicated list while preserving the order of first occurrences. Args: emails (list[str]): A list of email strings. Returns: list[str]: A list of unique, normalized email strings. """ result = [] # List to store the normalized unique emails seen = set() # Set to track normalized emails for deduplication for email in emails: # Normalize the email: convert to lowercase and strip whitespace normalized = email.lower().strip() # If the normalized email hasn't been seen, add it to the result if normalized not in seen: result.append(normalized) seen.add(normalized) # Mark it as seen return result # Example usage: emails_list = ["Example@example.com", "example@example.com", " EXAMPLE@EXAMPLE.COM ", "another@example.com", "Example@example.com"] normalized_unique_list = deduplicate_and_normalize(emails_list) print(normalized_unique_list) # Output: ['example@example.com', 'another@example.com']Explanation:
- Normalization: Each email is converted to lowercase using
.lower()and any leading/trailing whitespace is removed using.strip(). This ensures that variations like "Example@example.com" and "example@example.com" are treated as the same. - Deduplication: A set (
seen) is used to track normalized emails. If a normalized email is not in the set, it's added to the result list and the set. - Order Preservation: The result list maintains the order of the first occurrence of each unique normalized email.
- Edge Cases Handled:
- Empty list: Returns an empty list.
- Single element: Returns a list with the normalized version.
- All duplicates: Returns a list with one normalized email.
This function assumes that the input is a list of strings. If you need additional normalization rules (e.g., handling subdomains or validation), let me know!
- Normalization: Each email is converted to lowercase using