Sets – Advanced (frozen sets, set comprehensions), online

Six activities your students do on their own devices. See who's finished, and their scores.

Sets – Advanced (frozen sets, set comprehensions) in one minute

What students need to know

Curly braces with a single expression (no :) creates a set comprehension. frozensets are hashable and can be used as dictionary keys.

frozenset() creates a set that cannot be changed after creation - like a tuple vs list. Frozen means locked - no add(), remove(), or any mutation methods.

Mistakes students make

  • Square brackets make a list comprehension. Use curly braces {} for a set comprehension.
  • Frozen sets are immutable — they have no add() method.
  • Regular sets are mutable and can't be dict keys. Use frozenset({1, 2}) as the key instead.
  • Use == for comparison in conditions, not = (which is assignment).
PREVIOUS · MODULE 62Dictionaries – Advanced (comprehensions, merging)
YOU ARE HERE · MODULE 63Sets – Advanced (frozen sets, set comprehensions)

Discover other journeys with this module

What students will learn in this module

Every question in Module 63

Quick questions

  1. {x**2 for x in range(4)} creates?A[0, 1, 4, 9]B{0, 1, 4, 9}
  2. What is a frozenset?AA sorted setBAn immutable set
  3. Can you add to a frozenset?ANo it's immutableBYes
  4. Can a frozenset be a dict key?AYes it's hashableBNo
  5. Can a regular set be a dict key?ANo sets are mutableBYes

Key terms

Students type the meaning of:

  • Set comprehension
  • frozenset
  • Conditional comprehension
  • frozenset as key

Match the pairs

frozenset({1,2}).add(3)Match it to what it does
[x for x in range(5)]Match it to what it does
{x**2 for x in range(5)}Match it to what it does
frozenset({1, 2, 3})Match it to what it does
len({1, 2, 2, 3})Match it to what it does
{x for x in range(6) if x%2==0}Match it to what it does

Fill in the blanks

  1. squares = {x**2 ___ x in range(5)}
  2. evens = {x for x in range(10) __ x % 2 == 0}
  3. fs = _________(  {1, 2, 3}  )
  4. unique = ___(['a', 'b', 'a'])
  5. d = {_________({1, 2}): 'pair'}

Spot the error

Question 1

Anumbers = [1, 2, 3, 4, 5]Bsquares = [x**2 for x in numbers]Cprint('Squares:', squares)Dprint('Done')

Question 2

Afs = frozenset({1, 2, 3})Bfs.add(4)Cprint('Frozen:', fs)Dprint('Done')

Question 3

Akey = frozenset({1, 2})Bd = {{1, 2}: 'pair'}Cprint('Dict:', d)Dprint('Done')

Question 4

Anumbers = range(10)Bevens = {x for x in numbers if x % 2 = 0}Cprint('Evens:', evens)Dprint('Done')

Question 5

Aunique = set('hello')Bword = 'hello'Cprint(unique)  # expects {'hello'}Dprint('Done')