Fundamentals 12 min read

Mastering Python Sequence Functions for API Automation

This article walks through eight essential Python built‑in sequence functions—len, range, enumerate, reversed, sorted, zip, map, and filter—showing concrete API‑automation scenarios, step‑by‑step code examples, and practical tips for handling lists, generating test data, and filtering results efficiently.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Mastering Python Sequence Functions for API Automation

When writing API automation scripts, you constantly deal with sequences such as request parameter lists, response arrays, bulk test case collections, and performance‑test timing records. Python’s built‑in sequence utilities act like a Swiss‑army knife for these tasks, allowing you to shrink dozens of lines of code into a few concise, fast statements.

1. len() : Guarding against out‑of‑range errors and assertions

Use case: After calling a list‑query API, you need to assert that the returned list contains exactly 10 items and also protect against empty lists before indexing.

# Basic usage: assert list length
response_data = ["user1", "user2", "user3"]
assert len(response_data) == 3, f"Expected 3 items, got {len(response_data)}"
print("List length assertion passed")

# Advanced usage: defensive extraction
logs = []
if len(logs) > 0:
    print(f"Latest log: {logs[-1]}")
else:
    print("Log list empty, skip extraction")

2. range() : Bulk generation of test data

Use case: Simulate 100 concurrent users or create 100 test order payloads with sequential IDs.

# Basic usage: generate 10 test user IDs
user_ids = [f"user_{i}" for i in range(1, 11)]
print(f"Generated users: {user_ids[:3]}...")

# Advanced usage: even page numbers for pagination
page_numbers = list(range(2, 21, 2))
print(f"Even page numbers: {page_numbers}")

3. enumerate() : Indexed logging of test results

Use case: When printing results of a multi‑API test suite, include an index for easy issue tracing.

# Basic usage: indexed test output
apis = ["/login", "/get_user", "/logout"]
for index, api in enumerate(apis):
    print(f"[{index}] Testing API: {api}")

# Advanced usage: start index at 1
results = ["PASS", "FAIL", "PASS"]
for idx, res in enumerate(results, start=1):
    print(f"Case {idx}: {res}")

4. reversed() : Reverse‑order log inspection

Use case: When an API error occurs, view the most recent five log entries, which are stored chronologically.

# Basic usage: reverse print logs
logs = ["10:00 login", "10:05 query order", "10:10 error"]
for log in reversed(logs):
    print(log)

# Advanced usage: take the latest two entries
recent_logs = list(reversed(logs))[:2]
print(f"Recent two logs: {recent_logs}")

5. sorted() : Ranking performance‑test timings

Use case: After a load test, identify the three slowest APIs for optimization.

# Basic usage: ascending sort
times = [150, 320, 110, 450, 200]
sorted_times = sorted(times)
print(f"Fastest response: {sorted_times[0]}ms")

# Advanced usage: sort dicts by a field in descending order
apis = [{"name": "login", "time": 150}, {"name": "query", "time": 450}]
slowest_apis = sorted(apis, key=lambda x: x["time"], reverse=True)
print(f"Slowest API: {slowest_apis[0]["name"]}")

6. zip() : Pairing parameters with expected values

Use case: Data‑driven testing where a list of inputs (e.g., users) must be matched with a list of expected status codes.

# Basic usage: pair inputs and expectations
users = ["admin", "guest"]
expected_codes = [200, 403]
for user, code in zip(users, expected_codes):
    print(f"User: {user} -> Expected code: {code}")

# Advanced usage: build a header dict
keys = ["Content-Type", "Authorization"]
values = ["application/json", "Bearer token123"]
headers = dict(zip(keys, values))
print(f"Generated headers: {headers}")

7. map() : Bulk cleaning of API response data

Use case: Remove surrounding whitespace from a list of strings returned by an API, or convert string IDs to integers.

# Basic usage: strip whitespace
raw_data = [" admin ", " user ", " token "]
clean_data = list(map(str.strip, raw_data))
print(f"Cleaned data: {clean_data}")

# Advanced usage: convert strings to ints
str_ids = ["101", "102", "103"]
int_ids = list(map(int, str_ids))
print(f"Converted IDs: {int_ids}")

8. filter() : Selecting failing test cases

Use case: After executing 100 API calls, extract those with non‑200 status codes for a failure report.

# Basic usage: filter non‑200 codes
status_codes = [200, 500, 200, 404, 201]
failed_codes = list(filter(lambda x: x != 200, status_codes))
print(f"Failed requests: {failed_codes}")

# Advanced usage: filter complex objects
logs = [{"api": "/login", "time": 120}, {"api": "/pay", "time": 3500}]
slow_logs = list(filter(lambda x: x["time"] > 1000, logs))
print(f"Timeout APIs: {slow_logs}")

Combination Techniques

By chaining these utilities, you can build powerful pipelines. For example, zip() + map() quickly creates default JSON payloads, while sorted() + filter() produces a performance‑test report that first discards fast requests and then ranks the slowest ones.

# zip + map: generate cleaned payload
fields = ["username", "password", "age"]
values = [" admin ", " 123456 ", " 18 "]
clean_payload = dict(zip(fields, map(str.strip, values)))
print(f"Cleaned payload: {clean_payload}")

# sorted + filter: top‑3 slow requests
times = [50, 300, 120, 450, 80]
slow_sorted = sorted(filter(lambda t: t > 100, times), reverse=True)
print(f"Top 3 slow requests: {slow_sorted[:3]}")

Tips: map() and filter() are lazy; wrap them with list() to realize the results. sorted() loads the whole list into memory—use heapq.nlargest() for very large datasets. zip() truncates to the shortest iterable; use itertools.zip_longest when lengths differ to avoid silent data loss.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

data-processingtestingapi-automationcode-examplesbuilt-insequence-functions
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

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.