Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Set intersection with `&`

Use `&` to find the elements two sets share. The same operator performs bitwise AND when both operands are integers.

Version: Python 3.12

Syntax

a & b

In Python 3.12, set intersection (indexed as set &) is written a & b. It creates a new set containing only elements that belong to both sets and leaves both operands unchanged. If they share no elements, the result is empty.

You can mix the built-in types set and frozenset. When you do, the result has the type of the left operand. If you have a plain list, use a.intersection(items): the method accepts an iterable, whereas a & items raises TypeError with a built-in set and a plain list.

With two int operands, & performs bitwise AND instead of set intersection. The keyword and is different again: it tests the truth value of the left operand and returns one of the operands, rather than computing an intersection.

Examples

a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a & b))
print(6 & 3)

Result

[2, 3]
2

The shared elements are `2` and `3`. The call to `sorted()` produces a sorted list for display; `a & b` itself returns a set. The second line shows the bitwise AND of `6` and `3`.

Related lessons

  • Python · Lesson 18 · Basic · Version: 3

Sources