Python中set(a) and set(b)与set(a) & set(b)结果不同的原因?
Why
set(a) and set(b) differs from set(a) & set(b) in Python The core difference comes down to the purpose of each operator:
1. & is the set intersection operator
This operator is purpose-built for sets to compute their mathematical intersection. It returns a new set containing only elements that exist in both input sets.
In your code:
set(nums1)equals{4, 9, 5}set(nums2)equals{8, 9, 4}set(nums1) & set(nums2)returns elements common to both sets:{9, 4}
2. and is a logical boolean operator
The and operator works across all Python objects, following simple truthiness rules:
- If the first operand is falsy (like an empty set,
None, or0), it returns the first operand. - If the first operand is truthy (non-empty set, non-zero number, etc.), it returns the second operand.
In your code:
set(nums1)is non-empty (truthy), soset(nums1) and set(nums2)just returns the second operand:set(nums2) = {8, 9, 4}. It does not compare set elements for overlap at all.
Breakdown of your code
nums2 = [9,4,9,8,4] nums1 = [4,9,5] # Evaluate "and" expression set1 = set(nums1) # {4,9,5} (truthy) set2 = set(nums2) # {8,9,4} a = set1 and set2 # Returns set2 because set1 is truthy # Evaluate intersection expression b = set1 & set2 # Returns elements present in both sets: {9,4} print(a) # {8, 9, 4} print(b) # {9, 4}
Key takeaways
- Use
&(or the.intersection()method) when you need to find common elements between sets. - Use
andonly for logical checks (e.g., verifying both sets are non-empty), not for set-specific operations.
内容的提问来源于stack exchange,提问作者Divide
相关产品推荐
相关产品推荐

