Interview question
What are Python sets used for and how are they different from lists? - Data Types and Data Structures Python sets का use क्या है और lists से कैसे अलग हैं?
Answer
# Sets store unique elements
my_set = {1, 2, 3, 2, 1} # Duplicates removed
print(my_set) # {1, 2, 3}
# No indexing
# print(my_set[0]) # TypeError
# Unordered
set1 = {3, 1, 2}
set2 = {1, 2, 3}
print(set1 == set2) # True - same elements
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2 # {1, 2, 3, 4, 5, 6}
intersection = set1 & set2 # {3, 4}
difference = set1 - set2 # {1, 2}
sym_diff = set1 ^ set2 # {1, 2, 5, 6}
# Fast membership testing - O(1)
large_set = set(range(1000000))
if 500000 in large_set: # Very fast!
print('Found')# Sets - unique elements
my_set = {1, 2, 3, 2, 1} # {1, 2, 3}
# No indexing या ordering नहीं
# Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2 # {1, 2, 3, 4, 5, 6}
intersection = set1 & set2 # {3, 4}
difference = set1 - set2 # {1, 2}
# Fast lookup - O(1)
large_set = set(range(1000000))
if 500000 in large_set: # बहुत fast
passWas this answer clear?