Fundamentals 7 min read

Understanding Python Comprehensions: Lists, Dictionaries, Sets, and Generators with Examples

Python comprehensions provide a concise, powerful way to create new data structures—lists, dictionaries, sets, and generators—from existing iterables, combining loops and conditional logic, and the article explains their syntax, usage, and includes practical code examples for dynamic parameter construction, data analysis, and testing scenarios.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python Comprehensions: Lists, Dictionaries, Sets, and Generators with Examples

Python comprehensions are compact and powerful constructs that allow you to generate new data structures such as lists, dictionaries, sets, or generators in a single line based on existing iterables, combining loops and conditional logic for flexible data processing.

List Comprehensions

List comprehensions are the most common form, used to create a new list from an iterable. Basic syntax: [expression for item in iterable if condition] where expression is evaluated for each item , item is the element from the iterable , which can be any iterable (list, tuple, set, dict, generator), and condition is an optional filter.

Dictionary Comprehensions

Dictionary comprehensions quickly build dictionaries. Syntax: {key_expression: value_expression for item in iterable if condition} where key_expression and value_expression define each key‑value pair. The remaining parts are analogous to list comprehensions.

Set Comprehensions

Set comprehensions produce a set (unordered, unique elements). Syntax: {expression for item in iterable if condition} .

Generator Expressions

Generator expressions are similar to list comprehensions but use parentheses, yielding a generator object that produces values on demand, saving memory. Syntax: (expression for item in iterable if condition) .

Scenario 1: Dynamic Parameter Construction

params_list = [(f"user_{i}", f"user_{i}@example.com") for i in range(1, 4)]
for username, email in params_list:
payload = {"username": username, "email": email}
print(f"Sending request with payload: {payload}")
# In real use, replace the print with requests.post(url, json=payload)

Output example:

Sending request with payload: {'username': 'user_1', 'email': '[email protected]'}
Sending request with payload: {'username': 'user_2', 'email': '[email protected]'}
Sending request with payload: {'username': 'user_3', 'email': '[email protected]'}

Scenario 2: Response Data Analysis

import requests
response = requests.get("https://api.example.com/users")
response_json = response.json()
# Extract all user IDs
user_ids = [user['id'] for user in response_json['data']]
print(f"Extracted User IDs: {user_ids}")

Output example:

Extracted User IDs: [1, 2, 3, 4, 5]

Scenario 3: Assertion Optimization

expected_roles = {"admin", "editor"}
response = requests.get("https://api.example.com/roles")
actual_roles = {role['name'] for role in response.json()}
assert expected_roles == actual_roles, f"Expected roles {expected_roles} but got {actual_roles}"
print("Roles assertion passed.")

Output example:

Roles assertion passed.

Scenario 4: Result Filtering and Error Detection

responses = [{"status_code": 200}, {"status_code": 404}, {"status_code": 200}]
failed_responses = [response for response in responses if response["status_code"] != 200]
if failed_responses:
print(f"Failed responses detected: {failed_responses}")
else:
print("All requests succeeded.")

Output example:

Failed responses detected: [{'status_code': 404}]

Scenario 5: Test Data Preparation

test_data_gen = (
{"id": idx, "name": f"Test_{idx}", "status": "active" if idx % 2 == 0 else "inactive"}
for idx in range(1, 6)
)
for data in test_data_gen:
print(f"Generated test data: {data}")
# In real use, replace the print with API request code using the generated data

Output example:

Generated test data: {'id': 1, 'name': 'Test_1', 'status': 'inactive'}
Generated test data: {'id': 2, 'name': 'Test_2', 'status': 'active'}
Generated test data: {'id': 3, 'name': 'Test_3', 'status': 'inactive'}
Generated test data: {'id': 4, 'name': 'Test_4', 'status': 'active'}
Generated test data: {'id': 5, 'name': 'Test_5', 'status': 'inactive'}
PythonlistdictionaryGeneratorcodesetcomprehensions
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

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.