7 Python One-Liners Every Expert Developer Should Know
Python is famous for its readability and simplicity, but true mastery comes with the ability to write concise, elegant, and powerful code. Here are seven one-liners that can help you become a Python ninja, showcasing the language's flexibility and expressiveness.
1. Swap Two Variables Without a Temporary Variable
x, y = y, x
Why It’s Cool
Python allows tuple unpacking, making swaps effortless without needing a temporary variable.
2. Read a File in One Line
lines = [line.strip() for line in open('file.txt')]
Why It’s Cool
This list comprehension reads a file, stripping whitespace, in a single line while keeping code neat and efficient.
3. Find the Most Frequent Element in a List
from collections import Counter
most_frequent = Counter(lst).most_common(1)[0][0]
Why It’s Cool
Counter
from collections
makes frequency counting intuitive and quick, perfect for data-heavy applications.
4. Check If a String is a Palindrome
is_palindrome = lambda s: s == s[::-1]
Why It’s Cool
Slicing with [::-1]
elegantly reverses a string, allowing a one-liner palindrome check.
5. Flatten a Nested List
flattened = [item for sublist in nested_list for item in sublist]
Why It’s Cool
This double list comprehension is a Pythonic way to flatten a list without recursion.
6. Get Unique Elements in a List (Preserving Order)
unique_list = list(dict.fromkeys(lst))
Why It’s Cool
Using dict.fromkeys()
keeps only unique elements while maintaining their original order.
7. Merge Dictionaries in Python 3.9+
merged_dict = dict1 | dict2
Why It’s Cool
The |
operator provides a clean and readable way to merge dictionaries.
These one-liners are not just cool tricks; they enhance code clarity, efficiency, and elegance. Have your own Python one-liner? Share it in the comments below!
No comments:
Post a Comment