← Python from Scratch Lesson 39 of 78 · 10 XP

Sets

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A set (set) is a collection of unique values with no order:

s = {3, 1, 3, 2}       # {1, 2, 3} — the duplicates are gone
empty = set()          # {} is an empty dictionary, not a set!
set("banana")          # {'b', 'a', 'n'}

What they're for:

  • removing duplicates: list(set(items));
  • checking quickly whether an item is there: x in s is instant even with a million items;
  • operations as in maths:
a = {1, 2, 3}
b = {2, 3, 4}
a | b      # {1, 2, 3, 4} — union
a & b      # {2, 3}       — intersection
a - b      # {1}          — difference

The order of the items isn't guaranteed. If you need an order, turn the set into a sorted list: sorted(s).

Task. Read two lines of words separated by spaces. Print the words that appear in both lines, in alphabetical order, separated by spaces. If there are none in common, print no common words.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.