Python is beautiful. And nothing shows that off quite like a well-crafted one-liner.
Whether you're wrangling data, automating boring stuff, or just trying to impress your coworkers during code review, these 10 Python one-liners will save you time and keystrokes. Let's dive in.
1. Swap Two Variables Without a Temp
a, b = b, a
Classic. No temporary variable needed. Python's tuple unpacking handles the swap in one clean move. This works because the right side is evaluated as a tuple (b, a) before assignment. Simple, elegant, and something every Pythonista should have in their back pocket.
2. Flatten a Nested List
flat = [item for sublist in nested_list for item in sublist]
Got a list of lists? This list comprehension flattens it into a single list. For example:
nested_list = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested_list for item in sublist]
# Result: [1, 2, 3, 4, 5, 6]
It reads like English once you get used to it: "for each sublist in the nested list, for each item in that sublist, give me the item." Works great for one level of nesting. For deeper structures, check out itertools.chain.from_iterable().
3. Reverse a String
reversed_str = my_string[::-1]
The slice notation [::-1] steps backward through the entire string. It's the Pythonic way to reverse any sequence — strings, lists, tuples, you name it.
"hello world"[::-1]
# Result: 'dlrow olleh'
Short, sweet, and surprisingly useful for palindrome checks and coding challenges.
4. Find the Most Frequent Element in a List
most_common = max(set(my_list), key=my_list.count)
This one's clever. It creates a set of unique elements, then uses max() with my_list.count as the key function to find which element appears most often.
my_list = ['apple', 'banana', 'apple', 'cherry', 'apple', 'banana']
most_common = max(set(my_list), key=my_list.count)
# Result: 'apple'
For large datasets, collections.Counter is more efficient, but for quick scripts this one-liner is hard to beat.
5. Read a File Into a List of Lines
lines = open('file.txt').read().splitlines()
Need to quickly grab all lines from a file? This does it without the trailing newline characters that readlines() leaves behind. Perfect for quick scripts and data processing.
lines = open('data.csv').read().splitlines()
print(lines[:3]) # peek at first 3 lines
For production code, you'd want a with statement for proper file handling. But for a quick REPL session or throwaway script? This is your friend.
6. Dictionary Comprehension From Two Lists
my_dict = dict(zip(keys, values))
Pair up two lists into a dictionary instantly. zip() creates tuples of corresponding elements, and dict() converts them.
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'Tokyo']
my_dict = dict(zip(keys, values))
# Result: {'name': 'Alice', 'age': 30, 'city': 'Tokyo'}
This is incredibly handy when parsing CSV headers with their row values, or mapping any two parallel sequences together.
7. Filter a List With a Condition
evens = [x for x in numbers if x % 2 == 0]
List comprehensions with conditions are one of Python's superpowers. This grabs only the even numbers from a list, but you can swap in any condition you need.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [x for x in numbers if x % 2 == 0]
# Result: [2, 4, 6, 8, 10]
Need something more complex? Chain conditions: [x for x in data if x > 0 and x < 100]. Clean, readable, fast.
8. Merge Two Dictionaries
merged = {**dict1, **dict2}
The double-splat operator ** unpacks dictionaries. When you combine two this way, you get a merged dictionary. If there are duplicate keys, dict2 wins.
defaults = {'color': 'blue', 'size': 'medium', 'theme': 'dark'}
user_prefs = {'color': 'green', 'font': 'mono'}
merged = {**defaults, **user_prefs}
# Result: {'color': 'green', 'size': 'medium', 'theme': 'dark', 'font': 'mono'}
In Python 3.9+, you can also use dict1 | dict2. Both are great for config merging and settings overrides.
9. Check If All (or Any) Elements Meet a Condition
all_positive = all(x > 0 for x in numbers)
all() returns True if every element satisfies the condition. Its sibling any() returns True if at least one does.
scores = [85, 92, 78, 95, 88]
all_passing = all(s >= 70 for s in scores) # True
has_perfect = any(s == 100 for s in scores) # False
These are perfect for validation logic. "Are all inputs valid?" "Does any item match?" Clean, expressive, and way better than writing manual loops with flag variables.
10. One-Line If/Else (Ternary Expression)
result = "even" if x % 2 == 0 else "odd"
Python's ternary expression packs an if/else into a single line. It reads almost like plain English.
age = 20
status = "adult" if age >= 18 else "minor"
# Result: 'adult'
Use it for simple conditional assignments. If your condition gets complex, break it into a regular if/else — readability always wins.
Wrapping Up
Python one-liners aren't just about showing off (though they're great for that too). They represent Python's philosophy of clean, readable, expressive code. Each of these snippets solves a real problem in a single line, and once they're in your muscle memory, you'll reach for them constantly.
A few tips for using one-liners effectively:
- Readability first. If a one-liner is hard to understand, break it up. Your future self will thank you.
- Know when to expand. One-liners are great for simple operations. Complex logic deserves multiple lines.
-
Practice in the REPL. Fire up
python3and experiment. That's the fastest way to internalize these patterns.
Got a favorite Python one-liner I missed? Drop it in the comments — I'm always looking to add to my toolkit.
Happy coding! 🐍
Top comments (0)