liveBook · Manning

Set

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A set is a collection that contains distinct elements without assigning significance to their order.

A set stores distinct elements without treating their order as significant. In Python, it is useful when a program needs a unique collection, such as the words gathered from several input files. section 20.1.3 section 20.3.4

Collecting unique words

Create an empty set, clean each input word, and add it with words.add(word). Repeated words collapse into one element; Python displays the result with curly braces. section 20.3.4 section 20.1.3

words = set()
for fh in args.file:                                                        #1
    for line in fh:                                                         #2
        for word in filter(word_len, map(clean, line.lower().split())):     #3
            words.add(word.title())                                         #4

A compact implementation shows how files, lines, cleaning, length filtering, title casing, and set insertion build a unique word collection. section 20.3.4

Sets also support operations beyond deduplication. Set intersection finds values shared by two sets, such as the numbers 5 through 9 in overlapping ranges. section 20.1.3

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains creation, insertion, deduplication, display, and intersection, while deferring the wider set API to documentation.
Examples
Demonstrates unique words from files and shared numbers from overlapping integer ranges.
What you can do after
Apply it via Python to deduplicate processed data and find shared values between collections.
How it connects
Connects sets with lists, dictionaries, string processing, filtering, and set intersection.

Also explained in

Compare how 15 books explain set →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.