Comprehensions
Comprehensions are a concise way to generate lists, dictionaries, and sets from existing data. They combine iteration and transformation into a single expression, making them ideal for data processing in formulas.
List Comprehensions
A list comprehension builds a new list by applying an expression to each item in an iterable:
[expression for variable in iterable]
Basic Examples
Clean up comma-separated tags:
[x.strip() for x in [tags].split(',')]
Splits the tags field by commas, then strips whitespace from each tag. If tags is 'bug, urgent , frontend ', the result is ['bug', 'urgent', 'frontend'].
Convert a string list to integers:
[int(x) for x in [numbers].split(',')]
Splits the numbers field and converts each part to an integer. '1,2,3,4' becomes [1, 2, 3, 4].
Uppercase each category:
[item.upper() for item in [categories].split(';')]
Splits by semicolons and converts each category to uppercase. 'hardware;software;network' becomes ['HARDWARE', 'SOFTWARE', 'NETWORK'].
Extract a field from a list of records:
[record.get('name') for record in record_list]
Extracts the name field from each dictionary in record_list.
Build formatted strings:
[str(i + 1) + '. ' + item for i, item in enumerate(my_list)]
Creates a numbered list. ['apple', 'banana'] becomes ['1. apple', '2. banana'].
Filtered Comprehensions
Add an if clause to include only items that meet a condition:
[expression for variable in iterable if condition]
Examples
Remove empty tags:
[x for x in [tags].split(',') if x.strip() != '']
Filters out any empty strings after splitting. 'bug,,urgent,,' produces ['bug', 'urgent'].
Filter records by status:
[x for x in record_list if x.get('status') == 'active']
Returns only the records where the status field is 'active'.
Filter by string length:
[item for item in my_list if len(item) > 3]
Keeps only items longer than 3 characters. ['a', 'bb', 'ccc', 'dddd', 'eeeee'] becomes ['dddd', 'eeeee'].
Select non-null values:
[x for x in [field1, field2, field3] if x is not None]
Collects only the fields that have values, discarding nulls.
Combine filtering and transformation:
[x.strip().lower() for x in [tags].split(',') if x.strip()]
Splits tags, removes empty entries, and normalizes each tag to lowercase.
Dictionary Comprehensions
Dictionary comprehensions generate key-value mappings:
{key_expr: value_expr for variable in iterable}
Examples
Build a lookup dictionary from a list of records:
{item['id']: item['name'] for item in record_list}
Creates a dictionary mapping each record's id to its name. Useful for building lookup tables.
Transform dictionary values:
{k: v.upper() for k, v in my_dict.items()}
Creates a new dictionary with all values converted to uppercase while keeping the same keys.
Index a list into a dictionary:
{str(i): item for i, item in enumerate(my_list)}
Converts a list into a dictionary with string indices as keys. ['a', 'b', 'c'] becomes {'0': 'a', '1': 'b', '2': 'c'}.
Filter while building a dictionary:
{k: v for k, v in my_dict.items() if v is not None}
Creates a copy of the dictionary with all null values removed.
Swap keys and values:
{v: k for k, v in my_dict.items()}
Reverses a dictionary so that values become keys and keys become values.
Set Comprehensions
Set comprehensions produce collections of unique values:
{expression for variable in iterable}
Examples
Get unique lowercase tags:
{x.lower().strip() for x in [tags].split(',')}
Splits tags, normalizes them, and deduplicates. 'Bug, bug, URGENT, urgent' becomes {'bug', 'urgent'}.
Collect unique categories from records:
{item['category'] for item in record_list}
Extracts the category value from each record, automatically removing duplicates.
Unique first characters:
{name[0].upper() for name in name_list if name}
Gets the unique uppercase first letters from a list of names.
Nested Comprehensions
You can use multiple for clauses to iterate over combinations:
[expr for x in outer for y in inner]
Examples
Generate coordinate pairs:
[[x, y] for x in range(3) for y in range(3)]
Produces [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]].
Collect all field names across records:
[field for record in record_list for field in record.keys()]
Flattens all field names from a list of record dictionaries into a single list.
Flatten a list of lists:
[item for sublist in nested_list for item in sublist]
Converts [[1, 2], [3, 4], [5, 6]] into [1, 2, 3, 4, 5, 6].
Combine with filtering:
[field for record in record_list for field in record.keys() if field != 'sys_id']
Collects all field names except sys_id from every record.
Comprehensions with Conditionals
You can include inline if/else expressions inside the output expression (distinct from the filter if):
[x.upper() if len(x) > 3 else x for x in my_list]
Uppercases items longer than 3 characters, leaves shorter ones unchanged.
['High' if int(p) <= 2 else 'Normal' for p in priorities]
Maps a list of numeric priority strings to labels.
Practical Tips
- Use comprehensions instead of loops -- since formulas are single expressions, comprehensions are the primary way to iterate over data.
- Chain with
.join()-- combine a list comprehension with string joining:', '.join([x.strip() for x in [tags].split(',') if x.strip()]). - Keep it readable -- if a comprehension becomes too complex, consider breaking the logic into multiple steps using the Assign Variables step.
- Watch for performance -- comprehensions over very large lists will take longer to evaluate. For most migration scenarios, this is not a concern.
Next Steps
- See all available built-in functions in Available Built-in Functions
- Return to basics with Introduction to Formulas
Comments
0 comments
Please sign in to leave a comment.