
Python is well-known for its clean syntax and powerful one-liners. Whether you’re building scripts, automating tasks, or crunching data, Python one-liners can help you write concise, readable, and efficient code.
In this article, we’ll explore 50 practical Python one-liners that every developer should know—categorized by use case so you can find exactly what you need, fast.
List and Comprehension One-Liners
- Create a list of numbers from 0 to 9
nums = [x for x in range(10)]
- Get squares of even numbers from 0 to 9
squares = [x**2 for x in range(10) if x % 2 == 0]
- Flatten a 2D list
flat = [item for sublist in matrix for item in sublist]
- Reverse a list
rev = my_list[::-1]
- Remove duplicates from a list
unique = list(set(my_list))
- Sort a list of tuples by second element
sorted_list = sorted(my_list, key=lambda x: x[1])
- Get common elements in two lists
common = list(set(list1) & set(list2))
- Get difference between two lists
diff = list(set(list1) - set(list2))
String Manipulation One-Liners
- Reverse a string
reversed_str = my_str[::-1]
- Check if a string is a palindrome
is_palindrome = s == s[::-1]
- Count vowels in a string
vowel_count = sum(c in 'aeiouAEIOU' for c in s)
- Remove all vowels from a string
no_vowels = ''.join(c for c in s if c.lower() not in 'aeiou')
- Capitalize first letter of each word
pythonCopyEditcapitalized = ' '.join(w.capitalize() for w in s.split())
- Find frequency of characters
pythonCopyEditfrom collections import Counter
freq = Counter(s)
Dictionary and Set One-Liners
- Swap keys and values in a dictionary
swapped = {v: k for k, v in d.items()}
- Merge two dictionaries (Python 3.9+)
pythonCopyEditmerged = dict1 | dict2
- Get keys with value greater than 10
filtered_keys = [k for k, v in d.items() if v > 10]
- Check for duplicate values in dictionary
has_duplicates = len(set(d.values())) < len(d.values())
- Filter dictionary by condition
filtered = {k: v for k, v in d.items() if v % 2 == 0}
Functional Programming One-Liners
- Sum of squares using
map()
andsum()
total = sum(map(lambda x: x**2, range(10)))
- Filter odd numbers
odds = list(filter(lambda x: x % 2 == 1, range(10)))
- Convert list of strings to uppercase
upper = list(map(str.upper, words))
- Get length of each word
lengths = list(map(len, words))
- Check if all elements are positive
all_positive = all(x > 0 for x in nums)
- Check if any element is zero
has_zero = any(x == 0 for x in nums)
File Handling One-Liners
- Read a file into a list of lines
lines = open('file.txt').read().splitlines()
- Write list to file
open('file.txt', 'w').writelines('\n'.join(lines))
- Count lines in a file
line_count = sum(1 for _ in open('file.txt'))
- Get all words in a file
words = open('file.txt').read().split()
- Find all lines containing a keyword
matches = [line for line in open('file.txt') if 'error' in line]
Numeric and Math One-Liners
- Check if number is prime
is_prime = lambda n: n > 1 and all(n % i for i in range(2, int(n**0.5)+1))
- Calculate factorial
from math import factorial
f = factorial(5)
- Calculate GCD of two numbers
from math import gcd
g = gcd(48, 18)
- Find max without using
max()
m = sorted(nums)[-1]
- Round a number to 2 decimal places
rounded = round(num, 2)
Date and Time One-Liners
- Get current date and time
from datetime import datetime
now = datetime.now()
- Get today’s date
from datetime import date
today = date.today()
- Calculate days between dates
delta = (date2 - date1).days
- Format date as string
formatted = datetime.now().strftime('%Y-%m-%d')
- Parse date string
parsed = datetime.strptime('2025-07-06', '%Y-%m-%d')
Miscellaneous One-Liners
- Generate a list of random numbers
import random
randoms = [random.randint(1, 100) for _ in range(10)]
- Get environment variable
import os
val = os.getenv('HOME')
- Check if a file exists
import os
exists = os.path.exists('file.txt')
- Create a list of tuples (index, value)
indexed = list(enumerate(my_list))
- Shuffle a list
random.shuffle(my_list)
- Zip two lists
zipped = list(zip(list1, list2))
- Unzip a list of tuples
a, b = zip(*zipped)
- Generate all combinations of a list
from itertools import combinations
combos = list(combinations(my_list, 2))
- Print a formatted string
print(f"Hello, {name}!")
- Run a simple HTTP server
python -m http.server
Final Thoughts
Python one-liners are not just clever tricks—they’re time-savers, code simplifiers, and productivity boosters. Whether you’re writing scripts, solving coding challenges, or building real-world applications, mastering these one-liners can help you write cleaner and more efficient code.
Start incorporating these into your projects, and over time, they’ll become second nature in your Python toolkit.

I’m Shreyash Mhashilkar, an IT professional who loves building user-friendly, scalable digital solutions. Outside of coding, I enjoy researching new places, learning about different cultures, and exploring how technology shapes the way we live and travel. I share my experiences and discoveries to help others explore new places, cultures, and ideas with curiosity and enthusiasm.