10 Useful Python One-Liners for Everyday Coding
Discover 10 practical Python one-liners that save time. Learn compact tricks for lists, dictionaries, and strings that keep your code clean and readable.
10 Useful Python One-Liners
Python rewards clear and compact code. These ten one-liners solve common tasks in a single readable line. Each one is short enough to remember and useful enough to reach for often.
1. Reverse a List
Slicing with a negative step flips any sequence instantly.
nums = [1, 2, 3, 4]
print(nums[::-1])2. Remove Duplicates
Turning a list into a set drops repeats, and wrapping it in sorted gives clean order.
items = [3, 1, 2, 3, 1]
print(sorted(set(items)))3. Swap Two Variables
Python swaps values without a temporary variable.
a, b = 1, 2
a, b = b, a
print(a, b)4. Sum of Squares
A generator expression inside sum keeps the math compact.
print(sum(x * x for x in range(1, 5)))5. Flatten a Nested List
A comprehension with two loops merges rows into one list.
matrix = [[1, 2], [3, 4]]
print([x for row in matrix for x in row])6. Count Word Frequency
Counter builds a tally from any sequence in one step.
from collections import Counter
print(Counter("banana"))7. Merge Two Dictionaries
The double star unpacks both dictionaries into a new one.
a = {"x": 1}
b = {"y": 2}
print({**a, **b})8. Find the Longest Word
The max function with a key picks the longest item.
words = ["cat", "elephant", "dog"]
print(max(words, key=len))9. Create a Number List
A comprehension builds a list of even numbers quickly.
print([n for n in range(10) if n % 2 == 0])10. Join a List Into Text
The join method turns a list of strings into one sentence.
parts = ["learn", "python", "fast"]
print(" ".join(parts))Use Them Wisely
One-liners are powerful, but clarity always comes first. If a single line becomes hard to read, a normal block is the better choice. Try each example in the playground and keep the ones that make your code cleaner.
By PythonExecutor Team