DEV Community

郑沛沛
郑沛沛

Posted on

10 Python One-Liners That Will Boost Your Productivity

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
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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 python3 and 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)