Practical Examples
Real-World Scenarios of List Uniqueness
1. Email Address Validation
def remove_duplicate_emails(email_list):
return list(dict.fromkeys(email_list))
## Example
emails = [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
]
unique_emails = remove_duplicate_emails(emails)
print(unique_emails)
2. User ID Deduplication
class UserManager:
def __init__(self, user_ids):
self.unique_users = list(set(user_ids))
def get_unique_users(self):
return self.unique_users
## Example
user_ids = [101, 102, 103, 101, 104, 102]
manager = UserManager(user_ids)
print(manager.get_unique_users())
Uniqueness Validation Techniques
Scenario |
Validation Method |
Use Case |
Simple Lists |
Set Conversion |
Remove duplicates quickly |
Complex Objects |
Custom Comparison |
Maintain unique complex elements |
Performance-Critical |
Hash-Based Methods |
Minimize computational overhead |
3. Transaction Log Cleaning
def clean_transaction_log(transactions):
seen_transactions = set()
cleaned_log = []
for transaction in transactions:
transaction_key = (transaction['id'], transaction['timestamp'])
if transaction_key not in seen_transactions:
seen_transactions.add(transaction_key)
cleaned_log.append(transaction)
return cleaned_log
## Example
transactions = [
{'id': 1, 'timestamp': '2023-01-01', 'amount': 100},
{'id': 2, 'timestamp': '2023-01-02', 'amount': 200},
{'id': 1, 'timestamp': '2023-01-01', 'amount': 100}
]
unique_transactions = clean_transaction_log(transactions)
print(unique_transactions)
Uniqueness Workflow
graph TD
A[Raw Data List] --> B{Contains Duplicates?}
B -->|Yes| C[Apply Uniqueness Method]
B -->|No| D[Return Original List]
C --> E[Unique Data List]
E --> F[Further Processing]
4. Advanced Filtering Technique
def filter_unique_by_key(data_list, key):
return list({item[key]: item for item in data_list}.values())
## Example
products = [
{'name': 'Laptop', 'brand': 'Dell', 'price': 1000},
{'name': 'Phone', 'brand': 'Apple', 'price': 800},
{'name': 'Tablet', 'brand': 'Dell', 'price': 500}
]
unique_brands = filter_unique_by_key(products, 'brand')
print(unique_brands)
Best Practices
- Choose appropriate uniqueness method
- Consider data structure complexity
- Optimize for performance
- Handle edge cases
By exploring these practical examples, developers using LabEx can effectively manage list uniqueness in various Python applications.