SyncAI.news, a Varaisys broadcasting
10 Python One-Liners That Will Make Your Code Cleaner and Faster
MM

Matthew Mayo

· 1 min read

EngineeringKDnuggets

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

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

@functools.cache

Original source

This story was published by KDnuggets and written by Matthew Mayo. SyncAI.news shows a preview; the complete article is on the publisher's site.

Read the full story on kdnuggets.com

Similar News