50 Python One-Liners Every Developer Should Know
Python's expressiveness lets you do incredible things in a single line. Here are 50 battle-tested one-liners covering file I/O, data structures, string manipulation, web requests, and more — all ready to copy and use.
File & System Operations
# 1. Read all lines from a file
lines = open('data.txt').read().splitlines()
# 2. Write a list to a file, one line per item
open('out.txt', 'w').write('\n'.join(my_list))
# 3. List all .py files recursively
py_files = [str(p) for p in __import__('pathlib').Path('.').rglob('*.py')]
# 4. Get file size in a human-readable format
size = lambda b: f"{b/1024**2:.1f} MB" if b > 1e6 else f"{b/1024:.1f} KB"
# 5. Create a directory if it doesn't exist
__import__('os').makedirs('output/reports', exist_ok=True)
# 6. Flatten a nested directory listing
all_files = [f for r,_,fs in __import__('os').walk('.') for f in fs]
# 7. Get the most recently modified file in a directory
latest = max(__import__('pathlib').Path('.').glob('*'), key=lambda p: p.stat().st_mtime)
Data Structures & Collections
# 8. Flatten a list of lists
flat = [item for sublist in nested for item in sublist]
# 9. Remove duplicates while preserving order
unique = list(dict.fromkeys(my_list))
# 10. Find the most frequent element in a list
most_common = max(set(my_list), key=my_list.count)
# 11. Group list items by a key function
groups = {k: list(v) for k, v in __import__('itertools').groupby(sorted(data, key=fn), key=fn)}
# 12. Transpose a matrix (list of lists)
transposed = list(zip(*matrix))
# 13. Merge two dictionaries (Python 3.9+)
merged = dict1 | dict2
# 14. Invert a dictionary (swap keys and values)
inverted = {v: k for k, v in original.items()}
# 15. Create a dictionary from two lists
d = dict(zip(keys, values))
# 16. Filter dictionary by value condition
filtered = {k: v for k, v in d.items() if v > threshold}
String Manipulation
# 17. Reverse a string
reversed_str = s[::-1]
# 18. Check if a string is a palindrome
is_pal = lambda s: s == s[::-1]
# 19. Count character frequency in a string
freq = {c: s.count(c) for c in set(s)}
# 20. Format a number with commas
formatted = f"{1234567:,}" # "1,234,567"
# 21. Slugify a string (URL-friendly)
slug = '-'.join(re.sub(r'[^\w\s-]', '', text.lower()).split())
# 22. Extract all numbers from a string
nums = [int(x) for x in re.findall(r'\d+', text)]
# 23. Title case without losing existing casing
titled = ' '.join(w[0].upper() + w[1:] for w in s.split())
# 24. Remove all whitespace from a string
no_ws = ''.join(s.split())
# 25. Truncate a string with ellipsis
trunc = lambda s, n: s[:n-3] + '...' if len(s) > n else s
List Comprehensions & Functional
# 26. Filter a list (keep even numbers)
evens = [x for x in nums if x % 2 == 0]
# 27. Map a function over a list
squared = [x**2 for x in nums]
# 28. Filter + map in one line
result = [x*2 for x in nums if x > 0]
# 29. Find the intersection of two lists
common = list(set(a) & set(b))
# 30. Find elements in list A not in list B
diff = list(set(a) - set(b))
# 31. Chunk a list into batches of size N
chunks = [lst[i:i+n] for i in range(0, len(lst), n)]
# 32. Create a range of floats
float_range = lambda start, stop, step: [start + i*step for i in range(int((stop-start)/step))]
Date, Time & Math
# 33. Get today's date in ISO format
today = __import__('datetime').date.today().isoformat()
# 34. Calculate days between two dates
days = (lambda d1,d2: (d2-d1).days)(__import__('datetime').date(2026,1,1), __import__('datetime').date.today())
# 35. Generate a list of dates in a range
dates = [__import__('datetime').date.today() + __import__('datetime').timedelta(days=i) for i in range(30)]
# 36. Factorial (functional approach)
fact = lambda n: __import__('math').prod(range(1, n+1))
# 37. Check if a number is prime
is_prime = lambda n: n > 1 and all(n % i for i in range(2, int(n**0.5)+1))
# 38. Convert bytes to a human-readable string
human = lambda b: f"{b/1<<30:.1f} GB" if b>=1<<30 else (f"{b/1<<20:.1f} MB" if b>=1<<20 else f"{b/1024:.1f} KB")
Web, JSON & APIs
# 39. Fetch JSON from a URL
data = __import__('json').loads(__import__('urllib.request').urlopen('https://api.example.com/data').read())
# 40. Pretty-print JSON
print(__import__('json').dumps(data, indent=2, ensure_ascii=False))
# 41. Download a file from a URL
__import__('urllib.request').urlretrieve('https://example.com/file.pdf', 'local.pdf')
# 42. Parse query string parameters from a URL
params = dict(__import__('urllib.parse').parse_qsl(__import__('urllib.parse').urlparse(url).query))
# 43. Encode a dict as URL query string
qs = __import__('urllib.parse').urlencode({'key': 'val', 'page': 1})
# 44. Extract domain from a URL
domain = __import__('urllib.parse').urlparse(url).hostname
Regex & Text Processing
# 45. Extract all email addresses from text
emails = __import__('re').findall(r'[\w.+-]+@[\w-]+\.[\w.-]+', text)
# 46. Validate an email address format
is_email = bool(__import__('re').match(r'^[\w.+-]+@[\w-]+\.[\w.-]+$', email))
# 47. Replace multiple spaces with a single space
clean = __import__('re').sub(r'\s+', ' ', text).strip()
# 48. Split a string on multiple delimiters
parts = __import__('re').split(r'[;|,]', 'a;b|c,d')
# 49. Extract text between two markers
between = __import__('re').findall(r'<tag>(.*?)</tag>', html)
# 50. Strip HTML tags from text
plain = __import__('re').sub(r'<[^>]+>', '', html)
Loved these one-liners? There's more where that came from.
The Python Productivity Toolkit bundles 50+ production-ready scripts with proper error handling, CLI interfaces, and documentation — everything you need to automate your workflow like a pro.
Get the Full Toolkit — $5Lifetime access · Free updates · 30-day money-back guarantee