bhylu.com

Advertisements

Python Sets

A set holds unique hashable elements and supports membership and set operations. It does not provide a positional sequence contract.

Understand the idea

Use a set for distinct tags or allowed choices when duplicate occurrences and sequence order are not part of the meaning. Set iteration order is not a promised insertion order. Sort only for a predictable display or test, and ensure the elements can be ordered by the chosen key.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

tags = {"python", "web", "python"}
print(sorted(tags))
print("web" in tags)

Read the result

The displayed unique tags are ['python', 'web'], and membership is True.

Try one change

Add an existing tag and verify that the number of unique elements does not grow.