You can get more done — and reclaim a few seconds of your life — when you stop writing second, third, or even fourth follow-up lines to the one you already typed perfectly.

Tired of all the typing? Are the keystrokes wearing you down? Want to get things done while saying less? Below are 10 Python one-liners that are practical and version-aware, each one an improvement over the typical multi-line alternative. They save time because you skip the second, third, or — *gasp!* — fourth line you’d otherwise write to follow up your first, perfectly typed line.
Keep in mind that each one-liner relies on a few assumptions. First, examples 2, 6, 9, and 10 assume that import itertools, import functools, and from collections import Counter appear earlier in your script. Second, pay attention to the minimum Python versions noted for each one-liner, since earlier versions will fail on examples 3, 5, 6, and 10.
Let’s get to the one-liners.
1. Remove Duplicates While Preserving Order
This replaces a manual loop with a unique set of items, and unlike list(set(items)), it keeps the original order intact.
unique = list(dict.fromkeys(items))
The one-liner builds a dictionary using the items as keys, which drops duplicates while preserving the order in which they first appeared (guaranteed since Python 3.7). The keys are then converted back into a list.
2. Flatten a List of Lists
This is faster and more readable than nested loops — or the common sum(nested, []) trick, which runs in quadratic time.
flat = list(itertools.chain.from_iterable(nested))
It walks through each sublist lazily, in order, and collects every element into a single flattened list.
3. Merge Dictionaries
This replaces .copy() followed by .update(), or the less readable {a, b} unpacking, with an operator whose intent is obvious at a glance (Python 3.9+).
merged = defaults | overrides
A new dictionary is created containing all keys from both dictionaries; when keys conflict, values from the right-hand dictionary win.
4. Check a Condition Across a Collection with Short-Circuiting
This stops at the first match rather than scanning the entire collection, making it cleaner and faster than a flag-setting loop.
has_negative = any(x < 0 for x in values)
It returns True as soon as any element satisfies the condition, and False if none do. all() is the inverse check.
5. Compute Once, Filter and Keep
The walrus operator avoids calling an expensive function twice — once to filter and once to keep the value — exposing and fixing a common hidden inefficiency in comprehensions (Python 3.8+).
results = [y for x in data if (y := transform(x)) is not None]
The one-liner applies transform to each element, assigns the result to y inline, and keeps only the results that aren’t None.
6. Add Instant Memoization to a Function
This single decorator line can turn exponential-time recursive functions or repeated expensive computations into near-instant lookups (Python 3.9+; on older versions use @lru_cache(maxsize=None)).
@functools.cache
It stores the return value for each unique set of arguments, then returns the stored result on repeat calls instead of recomputing it — a genuine time savings.
7. Transpose a Matrix
This swaps rows and columns in a single line, without index arithmetic or NumPy, making it ideal for quick tabular reshaping.
transposed = list(zip(*matrix))
Each row is unpacked as a separate argument to zip, which then groups the first elements of every row together, then the second elements, and so on, producing tuples of columns.
8. Find the Key with the Highest Value in a Dictionary
This replaces a loop that tracks a running maximum and its key.
best = max(scores, key=scores.get)
The code iterates over the dictionary’s keys and returns the key whose associated value is largest.
9. Get the Most Frequent Items
This replaces manual dictionary counting and sorting with an optimized, purpose-built standard library tool.
top3 = Counter(words).most_common(3)
The line counts occurrences of each element and returns a list of the three most common (item, count) pairs in descending order.
10. Split an Iterable into Fixed-Size Chunks
This removes the error-prone slicing arithmetic usually written for batching API calls or model inputs (Python 3.12+).
batches = list(itertools.batched(records, 100))
The code groups the iterable into tuples of up to 100 elements each; the final tuple holds whatever remains.
Wrapping Up
Notice how simple each of these entries is. There’s no magic — just in-the-trenches work, and the value lies in the expressiveness of each statement. I told you the time savings would add up right away, but you didn’t believe me, did you? You’re welcome.
Don’t forget to add this newly acquired coding-optimization skill to your resume. You’re welcome again.
Matthew Mayo (@mattmayo13) holds a master’s degree in computer science and a graduate diploma in data mining. As managing editor of KDnuggets & Statology, and contributing editor at Machine Learning Mastery, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.
- Make Sense of a 10K+ Line GitHub Repos Without Reading the Code
- This Python Library Can Run Pandas Workloads Up to 20x Faster
- 5 Docker Best Practices for Faster Builds and Smaller Images
- Gemma 3n: Smarter, Faster, and Offline-Ready
- Quantization and Pruning Methods to Make Your LLM Leaner
- Stop Writing Loops in Pandas: 7 Faster Alternatives to Try

