bhylu.com

Advertisements

Loop Sets

Iterate a set when you need to visit its distinct elements. Sort for presentation when users need a stable order.

Understand the idea

Iteration order is not a ranking or insertion history. Adding or removing elements from a set while traversing it can raise an error. Build another set or collect planned changes first. A set comprehension is useful for a straightforward transformation that still has unique-result semantics.

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

cities = {"Surat", "Nadiad", "Surat"}
for city in sorted(cities):
    print(city)

Read the result

Nadiad and Surat appear once each, in the order requested by sorted.

Try one change

Create a new set of case-folded city names without mutating the set being visited.