Fundamentals 7 min read

Python Comprehensions: List, Dictionary, Set, Generator and Interview Questions

This article explains Python's comprehension syntax—including list, dictionary, set, and generator expressions—provides multiple code examples, demonstrates advanced usage such as conditional and nested comprehensions, and presents a common interview question illustrating variable scope with lambda functions.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Comprehensions: List, Dictionary, Set, Generator and Interview Questions

Python offers a concise comprehension syntax that acts as syntactic sugar for creating sequences and mappings, allowing developers to write compact and expressive code.

1. List Comprehensions

List comprehensions generate lists using a single expression inside square brackets. Examples include creating a list of numbers, squaring each element, and defining a helper function for readability.

lis = [x for x in range(1,10)]
print(lis)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

lis = [x * x for x in range(1,10)]
print(lis)  # [1, 4, 9, 16, 25, 36, 49, 64, 81]

def squared(x):
    return x*x
lis = [squared(i) for i in range(1,10)]
print(lis)  # [1, 4, 9, 16, 25, 36, 49, 64, 81]

lis = []
for i in range(1,10):
    lis.append(i*i)
print(lis)  # [1, 4, 9, 16, 25, 36, 49, 64, 81]

List comprehensions can also include conditional filters, multiple loops, and other tricks such as swapping keys and values in a dictionary.

lis = [x * x for x in range(1,11) if x % 2 == 0]
print(lis)  # [4, 16, 36, 64, 100]

lis = [a + b for a in '123' for b in 'abc']
print(lis)  # ['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']

dic = {"k1":"v1", "k2":"v2"}
a = [v+":"+k for k,v in dic.items()]
print(a)  # ['v1:k1', 'v2:k2']

2. Dictionary Comprehensions

Using curly braces with a key‑value expression creates a dictionary comprehension.

dic = {x: x**2 for x in (2,4,6)}
print(dic)  # {2: 4, 4: 16, 6: 36}

mcase = {'a':10, 'b':34, 'A':7, 'Z':3}
mcase_frequency = {k.lower(): mcase.get(k.lower(),0) + mcase.get(k.upper(),0) for k in mcase.keys() if k.lower() in ['a','b']}
print(mcase_frequency)  # {'a': 17, 'b': 34}

mcase = {'a':10, 'b':34}
mcase_frequency = {v:k for k,v in mcase.items()}
print(mcase_frequency)  # {10: 'a', 34: 'b'}

3. Set Comprehensions

Set comprehensions look like dictionary comprehensions but only contain a single expression, producing a set.

a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)  # {'d', 'r'}

4. Generator (Tuple) Comprehensions

Parentheses create a generator expression, not a tuple. To obtain a tuple, wrap the generator with tuple() .

tup = (x for x in range(9))
print(tup)  # <generator object ...>
print(type(tup))  # <class 'generator'>

tup = tuple(x for x in range(9))
print(tup)  # (0, 1, 2, 3, 4, 5, 6, 7, 8)
print(type(tup))  # <class 'tuple'>

5. Interview Question

The following code demonstrates how variable scope interacts with list comprehensions and lambda functions:

result = [lambda x: x + i for i in range(10)]
print(result[0](10))  # 19

All functions in result return 19 because the lambda captures the variable i by reference, and after the loop finishes i equals 9. To capture the current loop value, bind it as a default argument:

result = [lambda x, i=i: x + i for i in range(10)]
print(result[0](10))  # 10

This illustrates an important pitfall when using comprehensions with closures in Python.

Pythonlambdainterviewgeneratorlist comprehensioncomprehensiondictionary-comprehensionset-comprehension
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.