A list comprehension provides a concise way to create lists in Python. It replaces bulky
forloops and.append()statements with a single, highly readable line of code.
# Instead of setting up an empty list, looping, and filtering, you write the logic directly inside brackets: new_list = [expression for item in iterable if condition]
squares = [x * x for x in range(5) if x % 2 == 0] # [0, 4, 16]
lengths = {w: len(w) for w in ["ai", "llm"]} # {'ai': 2, 'llm': 3}
unique = {x % 3 for x in range(10)} # {0, 1, 2}A dictionary comprehension uses curly braces
{}and requires akey: valuepair format separated by a colon.
numbers = [1, 2, 3, 4]
cube_dict = {x: x ** 3 for x in numbers}
# Output: {1: 1, 2: 8, 3: 27, 4: 64}
# Using a condition (only mapping even numbers)
even_cubes = {x: x ** 3 for x in numbers if x % 2 == 0}
# Output: {2: 8, 4: 64}
A set comprehension also uses curly braces
{}, but it only specifies a single value (just like a list comprehension). Because it creates a set, it will automatically remove duplicates and ignore order.
# Extracting unique lengths of words, ignoring case
words = ["Python", "java", "Go", "JAVA", "python"]
# Notice the duplicates will be filtered out automatically
word_lengths = {len(w.lower()) for w in words}
print(word_lengths)
# Output: {2, 4, 6}