Sets

A set stores unique values.

The duplicate "cat" is kept only once.

Sets are useful for uniqueness and membership tests.

Membership

Use in to ask whether a value is present:

Output:

True
False

This is useful when you need to ask "have we seen this before?"

Building a Set

You can build a set from a list:

The printed order may not match the input order. A set is about membership, not sequence order.

Unique words

A set removes duplicates, then membership checks become direct.

Runs locally with Python in your browser.

Ready to run.

Adding Values

Use .add():

The second "cat" does not create a duplicate.

Sets Do Not Preserve Repeated Items

Do not use a set when you need stable order or repeated values. For ordered sequences, use a list.

Exercise: Membership check

What does this expression produce?

"fox" in {"cat", "dog"}
Choose one

Select one choice, then check.

HintInspect the members

The set contains only "cat" and "dog".

SolutionThe membership test is false

"fox" is not a member of the set, so the in expression produces False.

Sets Answer Membership Questions

Use a set when uniqueness or membership is the main question.