Python Set Methods
In this page:
set_name.add(item)
set_name.remove(item)
set_a.union(set_b)
set_a.intersection(set_b)
Elements जोड़ना और हटाना
add() एक बार में एक element डालता है; हटाते समय, जब तक missing element पर specifically exception चाहिए न हो, remove() से बेहतर discard() को prefer कीजिए — discard() से आप हर call को try/except में लपेटे बिना cleanup code लिख सकते हैं।
उदाहरण: Adding and Removing Elements
s = {1, 2, 3}
s.add(4) # adds one element
s.discard(10) # safe removal, no error for a missing element
print(s)
Set Union
union() दो sets को एक नए set में merge करता है और duplicates अपने-आप हट जाते हैं; | operator वही काम कम typing में करता है, और दोनों किसी भी संख्या में sets को chain करके (a | b | c) काम करते हैं।
उदाहरण: Set Union
a = {1, 2}
b = {2, 3}
print(a.union(b)) # merges both sets, dropping duplicates
print(a | b) # same result using the operator shorthand
Set Intersection
intersection() सिर्फ दोनों sets में common elements लौटाता है, और & इसका operator shorthand है — इसका typical use यह पता लगाना है कि दो articles किन tags को share करते हैं, या कौन-से users दो अलग groups में हैं।
उदाहरण: Set Intersection
a = {1, 2, 3}
b = {2, 3, 4}
print(a.intersection(b)) # elements common to both
print(a & b) # same result using the operator shorthand
Set Difference
difference() पहले set में मौजूद पर दूसरे में नहीं वाले elements लौटाता है (- इसका shorthand है), जबकि symmetric_difference() वे elements लौटाता है जो किसी एक set के लिए ही unique हैं — दोनों में confuse होना आसान है, इसलिए symmetric_difference को 'दो sets का XOR' मानकर सोचना मदद करता है।
उदाहरण: Set Difference
a = {1, 2, 3}
b = {2, 3}
print(a.difference(b)) # elements only in a
print(a.symmetric_difference(b)) # elements in exactly one of the two
Set Relationships Check करना
issubset() जाँचता है कि क्या किसी set के सारे elements दूसरे set में मौजूद हैं, issuperset() इसका उल्टा relationship जाँचता है, और isdisjoint() confirm करता है कि दो sets में कोई भी element common नहीं है — यह conflicting या overlapping selections जल्दी पहचानने में उपयोगी है।
उदाहरण: Checking Set Relationships
a = {1, 2}
b = {1, 2, 3}
c = {5, 6}
print(a.issubset(b)) # every element of a is in b
print(b.issuperset(a)) # the reverse relationship
print(a.isdisjoint(c)) # True, a and c share no elements
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: