30 Mind-Blowing Python One-Liners You Need to Try! 🚀

Python is famous for its simplicity and elegance, and one-liners are a perfect example of this.

30 Mind-Blowing Python One-Liners You Need to Try! 🚀
Photo by Anthony Indraus on Unsplash

Python is famous for its simplicity and elegance, and one-liners are a perfect example of this.

Here are 30 powerful Python one-liners that will save time, boost productivity, and impress your colleagues!


1. Reverse a string

print("Python"[::-1])  # Output: 'nohtyP'

2. Check if a string is a palindrome

is_palindrome = lambda s: s == s[::-1] 
print(is_palindrome("madam"))  # Output: True

3. Flatten a nested list

flat_list = lambda lst: [item for sublist in lst for item in sublist] 
print(flat_list([[1, 2], [3, 4], [5]]))  # Output: [1, 2, 3, 4, 5]

4. Find the most frequent element in a list

from collections import Counter 
most_frequent = lambda lst: Counter(lst).most_common(1)[0][0] 
print(most_frequent([1, 3, 2, 1, 4, 1, 3]))  # Output: 1

5. Swap two variables without a temporary variable

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

6. Remove duplicates from a list

unique = lambda lst: list(set(lst)) 
print(unique([1, 2, 2, 3, 4, 4, 5]))  # Output: [1, 2, 3, 4, 5]

7. Merge two dictionaries

d1, d2 = {"a": 1}, {"b": 2} 
merged = {**d1, **d2} 
print(merged)  # Output: {'a': 1, 'b': 2}

8. Find the intersection of two lists

common = lambda a, b: list(set(a) & set(b)) 
print(common([1, 2, 3], [2, 3, 4]))  # Output: [2, 3]

9. Find the difference between two lists

diff = lambda a, b: list(set(a) - set(b)) 
print(diff([1, 2, 3], [2, 3, 4]))  # Output: [1]

10. Convert a list of strings to uppercase

print([s.upper() for s in ["hello", "world"]])  # Output: ['HELLO', 'WORLD']

11. Sort a list of dictionaries by a key

students = [{"name": "Alice", "score": 90}, {"name": "Bob", "score": 80}] 
print(sorted(students, key=lambda x: x["score"]))   
# Output: [{'name': 'Bob', 'score': 80}, {'name': 'Alice', 'score': 90}]

12. Map values in a list using a lambda function

squared = list(map(lambda x: x**2, [1, 2, 3, 4])) 
print(squared)  # Output: [1, 4, 9, 16]

13. Filter even numbers from a list

evens = list(filter(lambda x: x % 2 == 0, range(10))) 
print(evens)  # Output: [0, 2, 4, 6, 8]

14. Compute the factorial of a number (recursive lambda)

fact = lambda n: 1 if n == 0 else n * fact(n-1) 
print(fact(5))  # Output: 120

15. Generate Fibonacci numbers

fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2) 
print(fib(10))  # Output: 55

16. Generate a list of Fibonacci numbers

from functools import reduce 
fib_list = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n-2), [0, 1]) 
print(fib_list(10))  # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

17. Transpose a matrix

matrix = [[1, 2, 3], [4, 5, 6]] 
print(list(zip(*matrix)))  # Output: [(1, 4), (2, 5), (3, 6)]

18. Check if all elements in a list satisfy a condition

all_positive = all(x > 0 for x in [1, 2, 3, 4]) 
print(all_positive)  # Output: True

19. Check if any element in a list satisfies a condition

any_negative = any(x < 0 for x in [1, 2, -3, 4]) 
print(any_negative)  # Output: True

20. Flatten a list of lists using sum

nested = [[1, 2], [3, 4], [5]] 
print(sum(nested, []))  # Output: [1, 2, 3, 4, 5]

21. Read a file in one line

print(open("file.txt").read())

22. Write to a file in one line

open("file.txt", "w").write("Hello, world!")

23. Count occurrences of a word in a file

print(open("file.txt").read().count("Python"))

24. Find all words in a string

import re 
words = re.findall(r"\b\w+\b", "Hello, world! How are you?") 
print(words)  # Output: ['Hello', 'world', 'How', 'are', 'you']

25. Generate a random string

import random, string 
print("".join(random.choices(string.ascii_letters, k=10)))  # Random 10-character string

26. Get the current date and time

from datetime import datetime 
print(datetime.now())

27. Find the execution time of a function

import time 
start = time.time() 
# Some code here 
print(f"Execution Time: {time.time() - start} seconds")

28. Check memory usage of an object

import sys 
print(sys.getsizeof([1, 2, 3]))  # Output: Memory in bytes

29. Get the most common word in a sentence

from collections import Counter 
sentence = "apple banana apple orange banana apple" 
print(Counter(sentence.split()).most_common(1))  # Output: [('apple', 3)]

30. Swap case of a string

print("Hello World!".swapcase())  # Output: 'hELLO wORLD!'

🚀 Conclusion

These 30 Python one-liners are just the beginning! Python’s simplicity makes it possible to write powerful and elegant code in just a single line. Try them out and level up your coding skills! 🚀

Which one was your favorite? Let me know in the comments! 👇🔥