Python is famous for its clean, readable syntax — and sometimes, a whole operation can be done in just one line of code.
Here are 10 fun, bite-sized examples to impress your friends (and maybe your future employer).
text = "Python"
reversed_text = text[::-1]
print(reversed_text) # nohtyP
How it works: [::-1]
slices the string from end to start.
word = "radar"
print(word == word[::-1]) # True
Why it’s cool: Palindrome check in one line using slicing.
items = [1, 2, 2, 3, 4, 4]
duplicates = list(set([x for x in items if items.count(x) > 1]))
print(duplicates) # [2, 4]
Tip: Convert to a set
to remove duplicates from the duplicates.
nested = [[1, 2], [3, 4], [5]]
flat = [x for sub in nested for x in sub]
print(flat) # [1, 2, 3, 4, 5]
Magic: List comprehension with two for
loops.
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5
Shortcut: No temp variable needed.
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2
print(merged) # {'a': 1, 'b': 3, 'c': 4}
Note: For older Python versions, use {**dict1, **dict2}
.
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
print(Counter(nums).most_common(1)[0][0]) # 3
Why it’s useful: Great for quick frequency analysis.
lines = [line.strip() for line in open("file.txt")]
Pro tip: Always close()
the file or use with open(...)
for safety.
squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, ..., 100]
Elegant: Comprehensions beat for
loops for short tasks.
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4, 6]
Lambda power: Anonymous functions for quick filtering.
Python’s expressiveness means you can often do more with less code.
These one-liners are not just party tricks — they’re handy tools for writing clean, efficient programs.