10 Python One-Liners Every Beginner Should Know

andreasPython Code3 weeks ago30 Views

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).


1. Reverse a String

text = "Python"
reversed_text = text[::-1]
print(reversed_text) # nohtyP

How it works: [::-1] slices the string from end to start.


2. Check if a String is a Palindrome

word = "radar"
print(word == word[::-1]) # True

Why it’s cool: Palindrome check in one line using slicing.


3. Find Duplicates in a List

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.


4. Flatten a List of Lists

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.


5. Swap Two Variables

a, b = 5, 10
a, b = b, a
print(a, b) # 10 5

Shortcut: No temp variable needed.


6. Merge Two Dictionaries (Python 3.9+)

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}.


7. Get the Most Common Element

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.


8. Read a File into a List

lines = [line.strip() for line in open("file.txt")]

Pro tip: Always close() the file or use with open(...) for safety.


9. Create a List of Squares

squares = [x**2 for x in range(1, 11)]
print(squares) # [1, 4, 9, ..., 100]

Elegant: Comprehensions beat for loops for short tasks.


10. Filter Even Numbers

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.


Conclusion

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.

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Loading Next Post...
Loading

Signing-in 3 seconds...