DEV Community

Stackcraft Studio
Stackcraft Studio

Posted on

5 Python one-liners I actually use every week

Most "Python one-liners" lists are party tricks you never use again. These five made it into my real scripts and stayed there.

1. Read a file into a list of clean lines

lines = [l.strip() for l in open("data.txt") if l.strip()]
Enter fullscreen mode Exit fullscreen mode

One pass, skips blank lines, no ceremony. I use this for every quick data job.

2. Count things without boilerplate

from collections import Counter
counts = Counter(words)
Enter fullscreen mode Exit fullscreen mode

counts.most_common(3) answers "what shows up most" in a single call. Stop writing histogram loops by hand.

3. Swap two variables

a, b = b, a
Enter fullscreen mode Exit fullscreen mode

No temp variable. Tuple unpacking is one of those small things that makes Python feel like Python.

4. Flatten a list of lists

flat = [x for row in grid for x in row]
Enter fullscreen mode Exit fullscreen mode

Read it as English: "x for each row in grid, for each x in row." Once it clicks, you stop reaching for nested loops.

5. Merge two dictionaries (3.9+)

config = defaults | overrides
Enter fullscreen mode Exit fullscreen mode

The | operator merges without mutating either dict. Clean defaults-plus-overrides in one line.


None of these are clever for the sake of clever. They survive code review, and that's the bar that matters. What one-liner do you actually use? Drop it in the comments. x

Top comments (1)

Collapse
 
sreno77 profile image
Scott Reno •

Very useful!