Interview question
What is the difference between a Python list, dictionary, and set in terms of use case? Use case के हिसाब से Python list, dictionary, और set में क्या अंतर है?
Answer
| Structure | Ordered? | Duplicates? | Access by | Best for |
|---|---|---|---|---|
| list | Yes | Allowed | Index | Ordered sequences, need duplicates |
| dict | Yes (insertion, Python 3.7+) | Keys unique, values can repeat | Key | Key-value lookups |
| set | No | Not allowed (auto-dedupes) | Membership only | Uniqueness, fast membership tests |
# List - ordered, allows duplicates
tags = ['python', 'web', 'python']
print(tags) # ['python', 'web', 'python']
# Dict - key-value pairs
user = {'name': 'John', 'age': 30}
print(user['name']) # John
# Set - unique values, fast membership check
unique_tags = set(tags)
print(unique_tags) # {'python', 'web'}
print('python' in unique_tags) # O(1) average - much faster than list 'in'
# Choosing based on need
visited_ids = set() # fast duplicate checking
for user_id in [1, 2, 1, 3]:
if user_id not in visited_ids:
visited_ids.add(user_id)
print(f'Processing {user_id}')| Structure | Ordered? | Duplicates? | Access | सबसे अच्छा |
|---|---|---|---|---|
| list | हाँ | Allowed | Index | Ordered sequences |
| dict | हाँ (insertion order) | Keys unique | Key | Key-value lookups |
| set | नहीं | Allowed नहीं | सिर्फ membership | Uniqueness, fast checks |
tags = ['python', 'web', 'python']
print(tags) # duplicates रहती हैं
user = {'name': 'John', 'age': 30}
print(user['name']) # John
unique_tags = set(tags)
print(unique_tags) # {'python', 'web'}
print('python' in unique_tags) # तेज़ O(1)Was this answer clear?