← Back to Blog

Building Lists and Sets the Short Way

The idea

You know the syntax. Now let's put it to work — with lists and sets, across real scenarios.

The only difference between a list comprehension and a set comprehension is the brackets.

Square brackets give you a list. Curly braces give you a set.

List comprehensions

Transform every element:

names = ["raven", "wolf", "ghost", "viper"]
upper = [name.upper() for name in names]
print(upper)

Output → ['RAVEN', 'WOLF', 'GHOST', 'VIPER']

Filter elements:

scores = [85, 74, 91, 63, 98, 55]
passing = [s for s in scores if s >= 80]
print(passing)

Output → [85, 91, 98]

Transform and filter at the same time:

scores = [85, 74, 91, 63, 98, 55]
labels = [f"{s} — passed" for s in scores if s >= 80]
print(labels)

Output → ['85 — passed', '91 — passed', '98 — passed']

From a string:

letters = [ch for ch in "RedHorn" if ch.isupper()]
print(letters)

Output → ['R', 'H']

From a list of strings — extract parts:

names = ["Raven Wolf", "Ghost Viper", "Bull Cruz"]
first_names = [name.split()[0] for name in names]
print(first_names)

Output → ['Raven', 'Ghost', 'Bull']

Set comprehensions

Same syntax — curly braces instead of square brackets. Duplicates removed automatically.

names = ["raven", "wolf", "raven", "ghost", "wolf"]
unique = {name.capitalize() for name in names}
print(unique)

Output → {'Ghost', 'Raven', 'Wolf'}

Filter into a set:

scores = [85, 74, 91, 63, 85, 91, 98]
unique_passing = {s for s in scores if s >= 80}
print(unique_passing)

Output → {98, 91, 85}

Duplicates gone. Only unique passing scores remain.

When to use which

  • Use a list comprehension when order matters or duplicates are valid
  • Use a set comprehension when you only care about unique values

When NOT to use a comprehension

Comprehensions are for building collections. Don't use them for side effects:

# WRONG — building a list just to print
[print(name) for name in names]

# CORRECT — use a regular loop
for name in names:
    print(name)

And don't nest them more than one level deep — it gets unreadable fast.

Heads up!

  • [...] — list comprehension, ordered, allows duplicates
  • {...} — set comprehension, unordered, unique values only
  • The if filters — elements that don't match are excluded entirely
  • Comprehensions are read left to right: expression → loop → filter

What you should understand now

  • List comprehension: [expr for item in iterable if condition]
  • Set comprehension: {expr for item in iterable if condition}
  • Transform, filter, or both — in one line
  • Set comprehension removes duplicates automatically
  • Don't use comprehensions for side effects — use a regular loop
[ login to bookmark ] // copied! 18 views · 2 min
// resources
Code Example list_set_comprehensions.py
← prev Comprehensions: A Shorter Way to Build Collections next → Building Dicts the Short Way
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.