Guide Python Beginner

12.2 Creating Sets

Why an empty set must use set() instead of {}, set literals, the set() constructor's automatic deduplication, and building sets from lists, tuples, and strings -- including the character-set gotcha.

2 min read

Empty Set

Must use set() — {} creates an empty dict, not a set. This is 12.17 Common Mistakes’ most common gotcha.

>>> s = set()
>>> s
set()

Set Literals

>>> s = {1, 2, 3}

set() Constructor

Converts any iterable into a set, automatically deduplicating — the same conversion mechanics covered generally in 8.6 Collection Type Conversion.

>>> set([1, 1, 2, 3])
{1, 2, 3}

Sets from Lists

>>> set([1, 2, 2, 3])
{1, 2, 3}

Sets from Tuples

>>> set((1, 2, 3))
{1, 2, 3}

Sets from Strings

Produces a set of individual characters — same as list("...") does for lists (see 10.2 Creating Lists) — not a set of words.

>>> set("hello")
{'h', 'e', 'o', 'l'}

Quick Interview Answer

“The one rule that trips almost everyone up at least once: {} is a dict literal, not an empty set — curly braces were claimed by dict syntax first, so an empty set has to be written set() explicitly. Every other creation path — a literal {...}, or set() around a list, tuple, or string — automatically deduplicates. The string case deserves a specific callout: set("hello") doesn’t produce a set of words, it produces a set of individual characters, exactly the way list("hello") does.”

Common Mistakes

  • Writing s = {} and getting a dict back — always use set() for an empty set.
  • Expecting set("hello world") to split on whitespace into a set of words — it splits into individual characters instead; use set("hello world".split()) for words.
  • Forgetting set() on a list/tuple with duplicates silently drops them — useful when intended, a bug when the original count mattered.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form