10 Python one-liners that showcase elegance, cleverness, and real-world usefulness.
text = “clcoding”
print(text[::-1])[::-1] slices the string backward. Simple, compact, wonderful.
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.
print(sorted(”listen”) == sorted(”silent”))Sorting characters reveals structural equivalence.
from collections import Counter
print(Counter(”banana”))The result beautifully tells how many times each item appears.
a, b = 5, 10
a, b = b, aPython makes swapping feel like a tiny magic trick.
flat = [x for row in [[1,2],[3,4]] for x in row]Nested list comprehension walks down layers elegantly.
data = open(”file.txt”).read()Great for quick scripts. Just remember to close or use with for production.
unique = list(set([1,2,2,3,4,4,5]))Sets remove duplicates like a digital comb.
nums = [1, 2, 3, 4]
nums.reverse()A one-liner that modifies the list in place.
age = 19
result = “Adult” if age >= 18 else “Minor”Readable, expressive, and close to natural language.