Resourcesโ€บPython Tricksโ€บ15 Python One-Liners That Will Impress Your Teammates
๐ŸPython Tricksโ€” 15 Python One-Liners That Will Impress Your Teammatesโฑ 5 min

15 Python One-Liners That Will Impress Your Teammates

Python's expressive syntax lets you do impressive things in a single line. Here are 15 genuinely useful one-liners with explanations.

๐Ÿ“…February 5, 2026โœTechTwitter.iopythonone-linerstricksproductivity

A Note on One-Liners

One-liners aren't just party tricks. Many of these replace 5-10 lines of code with a single, readable expression. Use them when they improve clarity โ€” avoid them when they don't.


1. Flatten a Nested List

nested = [[1, 2], [3, 4], [5, 6]]
flat = [x for sublist in nested for x in sublist]
# [1, 2, 3, 4, 5, 6]

# Or with itertools (handles arbitrary nesting):
from itertools import chain
flat = list(chain.from_iterable(nested))

2. Find Duplicates

data = [1, 2, 3, 2, 4, 3, 5]
duplicates = {x for x in data if data.count(x) > 1}
# {2, 3}

# Faster for large lists:
from collections import Counter
duplicates = {x for x, count in Counter(data).items() if count > 1}

3. Transpose a Matrix

matrix = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
transposed = list(zip(*matrix))
# [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

4. Most Common Element

from collections import Counter
data = ['apple', 'banana', 'apple', 'cherry', 'apple', 'banana']
most_common = Counter(data).most_common(1)[0][0]
# 'apple'

5. Merge Dicts (Python 3.9+)

defaults = {'debug': False, 'timeout': 30, 'retries': 3}
overrides = {'timeout': 60, 'verbose': True}
config = defaults | overrides
# {'debug': False, 'timeout': 60, 'retries': 3, 'verbose': True}
# Note: overrides wins on conflicts

6. Group Items by a Key

from itertools import groupby

data = [
    {'name': 'Alice', 'dept': 'Engineering'},
    {'name': 'Bob', 'dept': 'Marketing'},
    {'name': 'Carol', 'dept': 'Engineering'},
]

by_dept = {k: list(v) for k, v in groupby(sorted(data, key=lambda x: x['dept']), key=lambda x: x['dept'])}
# {'Engineering': [Alice, Carol], 'Marketing': [Bob]}

# Often cleaner with defaultdict:
from collections import defaultdict
by_dept = defaultdict(list)
for item in data:
    by_dept[item['dept']].append(item)

7. Swap Two Variables

a, b = 1, 2
a, b = b, a
# a=2, b=1 โ€” no temp variable needed

8. Read File into List of Lines

lines = open('file.txt').read().splitlines()
# No trailing newlines, strips blank lines from the result if you filter
lines = [l for l in open('file.txt').read().splitlines() if l.strip()]

9. Check if All/Any Elements Satisfy a Condition

scores = [85, 92, 78, 95, 88]

all_passing = all(s >= 70 for s in scores)  # True
any_perfect = any(s == 100 for s in scores)  # False
none_failing = not any(s < 70 for s in scores)  # True

10. Rotate a List

lst = [1, 2, 3, 4, 5]
n = 2
rotated = lst[n:] + lst[:n]
# [3, 4, 5, 1, 2]

# Rotate left by n:
rotated_left = lst[n:] + lst[:n]

# Rotate right by n:
rotated_right = lst[-n:] + lst[:-n]
# [4, 5, 1, 2, 3]

11. Unique Values Preserving Order

data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]

# set() is unordered โ€” loses original order
unique_unordered = list(set(data))

# dict.fromkeys() preserves insertion order (Python 3.7+)
unique_ordered = list(dict.fromkeys(data))
# [3, 1, 4, 5, 9, 2, 6]

12. Zip with Index (Enumerate)

fruits = ['apple', 'banana', 'cherry']

# Instead of range(len(fruits)):
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. cherry

13. Safe Dict Lookup with Default

config = {'host': 'localhost', 'port': 3000}

# KeyError if missing:
timeout = config['timeout']  # โŒ KeyError

# Returns default if missing:
timeout = config.get('timeout', 30)  # โœ… Returns 30

14. Flatten Dict to Dot Notation

def flatten(d, parent_key='', sep='.'):
    return {
        f"{parent_key}{sep}{k}" if parent_key else k: v
        for pk, pv in d.items()
        for k, v in (flatten(pv, pk, sep).items() if isinstance(pv, dict) else [(pk, pv)])
    }

nested = {'a': {'b': {'c': 1}, 'd': 2}, 'e': 3}
flatten(nested)
# {'a.b.c': 1, 'a.d': 2, 'e': 3}

15. Sort a List of Dicts

users = [
    {'name': 'Bob', 'age': 30},
    {'name': 'Alice', 'age': 25},
    {'name': 'Carol', 'age': 35},
]

# Sort by single key
by_age = sorted(users, key=lambda u: u['age'])

# Sort by multiple keys (age ascending, then name descending)
by_age_name = sorted(users, key=lambda u: (u['age'], u['name']))

# Reverse sort
oldest_first = sorted(users, key=lambda u: u['age'], reverse=True)

Key Takeaways

  • zip(*matrix) โ€” transpose any 2D structure
  • Counter.most_common() โ€” find frequent elements instantly
  • dict | other_dict โ€” merge dicts (Python 3.9+)
  • all() / any() with generators โ€” readable boolean checks on iterables
  • dict.fromkeys(iterable) โ€” deduplicate while preserving order
  • enumerate(iterable, start=1) โ€” iteration with index, cleaner than range(len(...))