ANI

10 Python One-Liners That Will Make Your Code Cleaner and Faster

Sick of all the typing? Punching keys got you down? Want to get things done while also being less wordy? You’ve come to the right place. Here, just below where you are reading right this very minute, are 10 Python one-liners that are practical and version-aware, with each showing an improvement over the typical multi-line alternatives. Get work done, and have seconds added back to your life since you won’t be writing second, third or — *gasp!* — fourth line follow-ups to your impeccably typed line numero uno.

Note that, while it is a single line doing the work in each instance, a few assumptions are needed. First, examples 2, 6, 9, and 10 assume import itertools, import functools, and from collections import Counter appear earlier in your script. Second, be aware of the minimum Python versions noted in each one-liner, since errors will be unavoidable with earlier version of Python in examples 3, 5, 6, and 10.

Now, let’s bring on those one-liners.

1. Remove Duplicates While Preserving Order

This line replaces a manual loop with a unique set of member items. It also keeps the original order, which list(set(items)) does not.

unique = list(dict.fromkeys(items))

This one-liner builds a dictionary from the items as keys, which discards repeats while keeping the order in which they first appeared (guaranteed since Python 3.7). The dictionary’s keys are then converted back to a list.

2. Flatten a List of Lists

This one-liner 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))

This iterates through each sublist, in lazy fashion, in sequence and collects every element into a single flattened list.

3. Merge Dictionaries

This line replaces .copy() followed by .update(), or the less readable {a, b} unpacking, with an operator whose meaning is immediately clear (Python 3.9+).

merged = defaults | overrides

A new dictionary is created with all keys from both dictionaries, and values from the right-hand dictionary win when keys conflict.

4. Check a Condition Across a Collection with Short-Circuiting

This line stops at the first match instead of scanning the whole collection. It is therefore both 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; False is returned if none do (and all() is the reverse check).

5. Compute Once, Filter and Keep

This line uses the walrus operator to avoid calling an expensive function twice — once to filter and once to keep the value. This exposes, and circumvents, 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; it then 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+; use @lru_cache(maxsize=None) on older versions).

@functools.cache

This code stores the return value for each unique set of arguments. Then it returns the stored result on repeat calls instead of recomputing it, for a real time savings.

7. Transpose a Matrix

This single line swaps rows and columns without index arithmetic or NumPy. This makes it an ideal tool for quick tabular reshaping.

transposed = list(zip(*matrix))

Each row is unpacked as a separate argument to zip. zip 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 line can replace a loop that tracks a running maximum and its key.

best = max(scores, key=scores.get)

The code iterates over the dictionary’s keys, returning 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, returning a list of the three most common (item, count) pairs in descending order.

10. Split an Iterable into Fixed-Size Chunks

This single line 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

Note the simplicity of each of these entries. There isn’t any magic happening; it’s just in-the-trenches work, and the value is the expressiveness of each statement. I told you all the time you’d be saving right off the bat, 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.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button