Useful One-Liners Reference
Practical single-line Python solutions for common data processing tasks.
Reverse a string using slice notation.
Used In: Palindrome checks, reversing tokens.
s[::-1]text = 'pipeline'
print(text[::-1])enilepipTime Complexity: O(N)
Related Methods: reversed()
Deduplicate a list while preserving order using dict.fromkeys().
Used In: Deduplicating customer IDs, event log entries.
list(dict.fromkeys(lst))ids = [3, 1, 2, 1, 3, 4]
unique = list(dict.fromkeys(ids))
print(unique)[3, 1, 2, 4]Time Complexity: O(N)
Related Methods: set()
dict.fromkeys() preserves order; set() is O(N) but unordered.
Flatten one level of nested lists into a single flat list.
Used In: Flattening API response arrays, combining CSV batches.
[item for sub in nested for item in sub]batches = [[1, 2], [3, 4], [5]]
flat = [x for sub in batches for x in sub]
print(flat)[1, 2, 3, 4, 5]Time Complexity: O(N)
Related Methods: itertools.chain.from_iterable()
Swap two variable values without a temporary variable.
Used In: Sorting algorithms, pointer swaps.
a, b = b, ax, y = 10, 20
x, y = y, x
print(x, y)20 10Time Complexity: O(1)
Related Methods: N/A
Count occurrences of each element using Counter.
Used In: Log level aggregation, word frequency, status monitoring.
Counter(iterable)from collections import Counter
logs = ['INFO', 'ERROR', 'INFO', 'WARNING', 'ERROR', 'ERROR']
print(Counter(logs).most_common(2))[('ERROR', 3), ('INFO', 2)]Time Complexity: O(N)
Related Methods: collections.Counter
Return a new dict sorted by its values in ascending or descending order.
Used In: Leaderboards, ranked reporting, priority queues.
dict(sorted(d.items(), key=lambda x: x[1]))scores = {'Alice': 88, 'Bob': 95, 'Carol': 72}
sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
print(sorted_scores){'Bob': 95, 'Alice': 88, 'Carol': 72}Time Complexity: O(N log N)
Related Methods: sorted(), operator.itemgetter()
Read a file's full contents into a string in one line.
Used In: Config loading, reading script templates.
open(path).read()from pathlib import Path
content = Path('config.json').read_text(encoding='utf-8')
print(type(content))<class 'str'>Time Complexity: O(N)
Related Methods: Path.read_text()
Remove empty and whitespace-only strings from a list.
Used In: CSV row cleaning, removing blank form fields.
[s for s in lst if s.strip()]fields = ['Alice', '', ' ', 'Bob', '']
clean = [s for s in fields if s.strip()]
print(clean)['Alice', 'Bob']Time Complexity: O(N)
Related Methods: filter()
Find all elements that appear more than once in a list.
Used In: Duplicate detection in user IDs, transaction dedup.
{x for x in lst if lst.count(x) > 1}ids = [1, 2, 3, 2, 4, 3, 5]
dupes = {x for x in ids if ids.count(x) > 1}
print(sorted(dupes))[2, 3]Time Complexity: O(N^2) with count(); use Counter for O(N)
Related Methods: collections.Counter
Merge two dicts into one (second dict overrides first on conflicts).
Used In: Config merging, default + override patterns.
{**d1, **d2} or d1 | d2 (Python 3.9+)defaults = {'timeout': 30, 'retries': 3}
overrides = {'retries': 5, 'debug': True}
config = {**defaults, **overrides}
print(config){'timeout': 30, 'retries': 5, 'debug': True}Time Complexity: O(N + M)
Related Methods: dict.update()
Join a list of strings into a single delimited string.
Used In: Building CSV rows, constructing SQL fragments, file paths.
sep.join(lst)parts = ['2026', '07', '12']
date_str = '-'.join(parts)
print(date_str)2026-07-12Time Complexity: O(N)
Related Methods: str.split()
Swap keys and values to create a reverse-lookup dictionary.
Used In: Reverse code lookups, ID-to-name mappings.
{v: k for k, v in d.items()}dept_code = {'Engineering': 'ENG', 'Data Science': 'DS'}
code_dept = {v: k for k, v in dept_code.items()}
print(code_dept['DS'])Data ScienceTime Complexity: O(N)
Common Mistakes: Duplicate values cause keys to be overwritten silently.
Transpose rows and columns of a 2D list using zip(*matrix).
Used In: Data pivoting, feature transposition.
list(map(list, zip(*matrix)))matrix = [[1, 2, 3], [4, 5, 6]]
transposed = list(map(list, zip(*matrix)))
print(transposed)[[1, 4], [2, 5], [3, 6]]Time Complexity: O(N*M)
Related Methods: zip()
Load a CSV file into a list of dicts using csv.DictReader.
Used In: Quick CSV loading in ETL scripts.
list(csv.DictReader(open(file)))import csv, io
data = 'name,dept\nAlice,DE\nBob,DS'
rows = list(csv.DictReader(io.StringIO(data)))
print(rows[0]){'name': 'Alice', 'dept': 'DE'}Time Complexity: O(N)
Related Methods: pandas.read_csv()
Get a nested value from a dict with a fallback instead of raising KeyError.
Used In: Parsing API responses, reading optional config fields.
d.get(key, default)response = {'status': 200, 'data': {'user': 'Alice'}}
name = response.get('data', {}).get('user', 'Unknown')
print(name)AliceTime Complexity: O(1)
Related Methods: dict.get()