10 Python One Liners That Will Blow Your Mind
Python has a reputation for being friendly, expressive, and surprisingly powerful. Some of the most delightful discoveries in Python are one-liners:
In this post, we’ll explore 10 Python one-liners that showcase elegance, cleverness, and real-world usefulness.
1. Reverse a String
text = “clcoding”
print(text[::-1])
[::-1] slices the string backward. Simple, compact, wonderful.
2. Find Even Numbers From a List
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
List comprehensions let you filter and transform with grace.
3. Check If Two Words Are Anagrams
print(sorted(”listen”) == sorted(”silent”))
Sorting characters reveals structural equivalence.
4. Count Frequency of Items
from collections import Counter
print(Counter(”banana”))
The result beautifully tells how many times each item appears.
5. Swap Two Variables Without Temp
a, b = 5, 10
a, b = b, a
Python makes swapping feel like a tiny magic trick.
6. Flatten a List of Lists
flat = [x for row in [[1,2],[3,4]] for x in row]
Nested list comprehension walks down layers elegantly.
7. Read a File in One Line
data = open(”file.txt”).read()
Great for quick scripts. Just remember to close or use with for production.
8. Get Unique Elements From a List
unique = list(set([1,2,2,3,4,4,5]))
Sets remove duplicates like a digital comb.
9. Reverse a List
nums = [1, 2, 3, 4]
nums.reverse()
A one-liner that modifies the list in place.
10. Simple Inline If-Else
age = 19
result = “Adult” if age >= 18 else “Minor”
Readable, expressive, and close to natural language.
Video Explanation: 10 Python One Liners That Will Blow Your Mind



Zip(**array1,**array2) is a great one too
Lotta old friends there. One thing to keep in mind about #1 when writing your own classes that implement __reversed__ as well as __getitem__ is that obj[::-1] obviously invokes the latter while reversed(obj) returns the former. And that the latter returns an item, obj[which], or a list of items, obj[range], whereas reversed(obj) returns a reversed generator object. That bit me once when I was implementing a "byte string" class.
Also, #6 only works if the outer list contains *only* unnested sub-lists. It fails if any item in the outer list isn't iterable. And it doesn't flatten sub-sub-lists. Handy in the right use case, though. They all are! I use #10 constantly, often for kwargs:
eggs = kwargs['spam'] if 'spam' in kwargs else 'bacon'
So often that I made:
KWARG = lambda nam,kw,typ,dflt: typ(kw[nam]) if nam in kw else dflt
To let me say:
eggs = KWARG('spam', 'bacon', str, kwargs)
cake = KWARG('cake', 42, int, kwargs)
Because I hated the error-prone double-entry, especially the quoted name.