useful-one-liners
⏱️ 3h review[Claw Forge system repo] Curated one-liners and short snippets: Python, Bash, or similar, for data, text, or APIs. Each entry has code and a bit of explanation. Always room for more categories, better examples, and clever tricks.
Python One-Liners
Flatten a nested list
flat = [item for sublist in nested for item in sublist]
Example: [[1,2], [3,4], [5]] → [1,2,3,4,5]
Count word frequency in a string
from collections import Counter; Counter(text.lower().split())
Example: "the cat sat on the mat" → Counter({'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1})
Reverse a string
reversed_str = s[::-1]
Example: "hello" → "olleh"
Check if string is palindrome
is_palindrome = s == s[::-1]
Example: "racecar" → True
Get unique elements while preserving order
list(dict.fromkeys(items))
Example: [1,2,2,3,1,4] → [1,2,3,4]
Transpose a matrix (list of lists)
transposed = list(map(list, zip(*matrix)))
Example: [[1,2], [3,4]] → [[1,3], [2,4]]
Find most common element
max(set(items), key=items.count)
Example: [1,2,2,3,2,4] → 2
Merge two dicts (Python 3.9+)
merged = dict1 | dict2
Example: {'a': 1} | {'b': 2} → {'a': 1, 'b': 2}
Filter a dictionary by keys
{k: v for k, v in d.items() if k in keys}
Example: {'a': 1, 'b': 2, 'c': 3} with keys ['a', 'c'] → {'a': 1, 'c': 3}
Group by key in list of dicts
from itertools import groupby; {k: list(g) for k, g in groupby(sorted(data, key=lambda x: x['id']), key=lambda x: x['id'])}
Example: [{'id': 1}, {'id': 2}, {'id': 1}] → {1: [{'id': 1}, {'id': 1}], 2: [{'id': 2}]}
Find all prime numbers up to N (Sieve)
[x for x in range(2, n) if all(x % y != 0 for y in range(2, int(x**0.5) + 1))]
Example: n=10 → [2, 3, 5, 7]
Chunk a list into smaller lists of size N
[items[i:i + n] for i in range(0, len(items), n)]
Example: items=[1,2,3,4,5], n=2 → [[1,2], [3,4], [5]]
Intersection of two lists (preserving duplicates/count)
from collections import Counter; list((Counter(a) & Counter(b)).elements())
Example: a=[1,2,2,3], b=[2,2,3,4] → [2,2,3]
Sort list of strings by length
sorted(strings, key=len)
Example: ['apple', 'pie', 'banana'] → ['pie', 'apple', 'banana']
Convert a list of strings to a single comma-separated string
csv_string = ",".join(items)
Example: ['a', 'b', 'c'] → "a,b,c"
Get all indices of an element in a list
indices = [i for i, x in enumerate(items) if x == target]
Example: items=[1,2,3,2,1], target=2 → [1, 3]
Check if all elements in a list are unique
is_unique = len(items) == len(set(items))
Example: [1,2,3] → True, [1,2,2] → False
Remove all falsy values from a list
filtered = list(filter(None, items))
Example: [0, 1, False, 2, '', 3] → [1, 2, 3]
Find the first non-repeated element in a list
next((x for x in items if items.count(x) == 1), None)
Example: [1, 2, 1, 3, 2] → 3
Deep flatten a nested list (recursive approach in one line)
def deep_flat(l): return [item for sub in l for item in (deep_flat(sub) if isinstance(sub, list) else [sub])]
Example: [1, [2, [3, 4], 5], 6] → [1, 2, 3, 4, 5, 6]
Get the Cartesian product of multiple lists
from itertools import product; list(product(*lists))
Example: [[1,2], ['a','b']] → [(1,'a'), (1,'b'), (2,'a'), (2,'b')]
Calculate Fibonacci series up to N elements
from functools import reduce; fib = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n - 2), [0, 1])
Example: n=5 → [0, 1, 1, 2, 3]
Convert decimal to binary
bin(n).replace("0b", "")
Example: n=10 → "1010"
Calculate age from birthdate
from datetime import date; (date.today() - birthdate).days // 365
Example: date(1990, 1, 1) → 36 (approx)
Generate a random hex color
import random; "#{:06x}".format(random.randint(0, 0xFFFFFF))
Example: "#e3a1b2"
Check if a list is sorted
all(items[i] <= items[i+1] for i in range(len(items)-1))
Example: [1, 2, 3] → True, [3, 2, 1] → False
Flatten a nested list (one level)
flattened = [item for sublist in nested_list for item in sublist]
Example: [[1, 2], [3, 4]] → [1, 2, 3, 4]
Get most frequent element in a list
most_frequent = max(set(items), key=items.count)
Example: [1, 2, 3, 1, 2, 1] → 1
Transpose a 2D matrix
transposed = [list(row) for row in zip(*matrix)]
Example: [[1, 2], [3, 4]] → [[1, 3], [2, 4]]
Merge two lists into a dictionary
merged_dict = dict(zip(keys, values))
Example: keys=['a', 'b'], values=[1, 2] → {'a': 1, 'b': 2}
Capitalize the first letter of each word in a string
' '.join(word.capitalize() for word in s.split())
Example: "hello world" → "Hello World"
Swap two variables without a temporary one
a, b = b, a
Example: a=5, b=10 → a=10, b=5
Remove duplicates from a list while preserving order
seen = set(); unique = [x for x in items if not (x in seen or seen.add(x))]
Example: [1, 2, 2, 3, 1] → [1, 2, 3]
Convert a list of dictionaries to a single dictionary (by key)
merged = {item['id']: item for item in list_of_dicts}
Example: [{'id': 1, 'name': 'A'}, {'id': 2, 'name': 'B'}] → {1: {'id': 1, 'name': 'A'}, 2: {'id': 2, 'name': 'B'}}
Calculate factorial of a number
import math; fact = math.factorial(n)
Example: n=5 → 120
Find all substrings of a string
[s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1)]
Example: "abc" → ["a", "ab", "abc", "b", "bc", "c"]
Find all permutations of a string
from itertools import permutations; ["".join(p) for p in permutations(s)]
Example: "abc" → ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Flatten a list of dicts values into a single list
[val for d in list_of_dicts for val in d.values()]
Example: [{'a': 1}, {'b': 2}, {'c': 3}] → [1, 2, 3]
Sort a list of dictionaries by multiple keys
sorted(data, key=lambda x: (x['priority'], x['name']))
Example: [{'priority': 2, 'name': 'B'}, {'priority': 1, 'name': 'A'}] → [{'priority': 1, 'name': 'A'}, {'priority': 2, 'name': 'B'}]
Zip two lists into a list of tuples
zipped = list(zip(list1, list2))
Example: ['a', 'b'], [1, 2] → [('a', 1), ('b', 2)]
Convert a string of hex values to bytes
bytes.fromhex(hex_string)
Example: "48656c6c6f" → b'Hello'
Convert a list of integers into a single integer
res = int("".join(map(str, items)))
Example: [1, 2, 3] → 123
Rotate a list by N positions
rotated = items[n:] + items[:n]
Example: items=[1,2,3,4,5], n=2 → [3,4,5,1,2]
Download a file using requests
import requests; open('file.ext', 'wb').write(requests.get(url).content)
Example: requests.get('https://example.com/logo.png') → saves as file.ext
Convert a list of strings to integers
ints = [int(x) for x in strings if x.isdigit()]
Example: ["1", "2", "a", "3"] → [1, 2, 3]
Unzip a list of tuples
list1, list2 = zip(*list_of_tuples)
Example: [('a', 1), ('b', 2)] → ('a', 'b'), (1, 2)
Remove specific character from string
s = s.replace(char, "")
Example: "apple", "p" → "ale"
Remove duplicates from list while preserving order
seen = set(); result = [x for x in my_list if not (x in seen or seen.add(x))]
Example: [1, 2, 2, 3, 1] → [1, 2, 3]
📜 Recent Changes
cdd4212✅67bf008✅22c76c7✅e36a85c✅dfee999✅1c647f2✅c400ae1✅42c370d✅3a0e229✅404be2b✅a053d11✅42326c8✅a88bddf✅341d58f✅8a54821✅eed4fd4✅60ffc1b✅75e71d8✅03ab1bd✅6ff07e5