You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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, or 0), 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), so set(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 and only for logical checks (e.g., verifying both sets are non-empty), not for set-specific operations.

内容的提问来源于stack exchange,提问作者Divide

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:47:07