Useful Python One Liners
Welcome to our page all about Python one-liners! Here, we’ve gathered short and useful Python one liners to do cool things. These one-liners cover a wide range of common tasks in Python. With this collection, you can learn how to do a lot with just a little code. It’s like finding shortcuts in a video game! We cover one-liners from different topics, from basic stuff to more advanced tricks. So, come on in and explore the world of Python one-liners—it’s fun, it’s useful, and it’s easier than you might think!

1. Swap two variables
One Liner:
a, b = b, aExample:
a = 5
b = 10
a, b = b, a
print(a)
print(b)
#Output:
10
52. Check if a string is a palindrome
One Liner:
is_palindrome = my_string == my_string[::-1]Example:
my_string = "madam"
is_palindrome = my_string == my_string[::-1]
print(my_string, "is", is_palindrome)
my_string = "madem"
is_palindrome = my_string == my_string[::-1]
print(my_string, "is", is_palindrome)
#Output
madam is True
madem is False3. Calculate the factorial of a number
One Liner:
factorial = 1 if n == 0 else functools.reduce(lambda x, y: x * y, range(1, n+1))Example:
import functools
n = 5
factorial = 1 if n == 0 else functools.reduce(lambda x, y: x * y, range(1, n+1))
print(factorial)
#Output
1204. Check if a number is prime
One Liner:
is_prime = n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))Example:
n = 5
is_prime = n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))
print(is_prime)
n = 6
is_prime = n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))
print(is_prime)
#Output:
True
False5. Check if a list is sorted
One Liner:
is_sorted = all(my_list[i] <= my_list[i + 1] for i in range(len(my_list) - 1))Example:
my_list = [1,2,3,4,5,6]
is_sorted = all(my_list[i] <= my_list[i + 1] for i in range(len(my_list) - 1))
print(is_sorted)
my_list = [1,2,3,4,6,5]
is_sorted = all(my_list[i] <= my_list[i + 1] for i in range(len(my_list) - 1))
print(is_sorted)
#Output
True
False6. Generate a list of squared numbers
One Liner:
squared_numbers = [x**2 for x in range(1, n+1)]Example:
n = 5
squared_numbers = [x**2 for x in range(1, n+1)]
print(squared_numbers)
#Output
[1, 4, 9, 16, 25]7. Remove whitespace from a string
One Liner:
no_whitespace = my_string.replace(" ", "")Example:
my_string = "String with White Spaces"
print(my_string)
no_whitespace = my_string.replace(" ", "")
print(no_whitespace)
#Output
String with White Spaces
StringwithWhiteSpaces8. Filter even numbers from a list
One Liner:
even_numbers = [x for x in my_list if x % 2 == 0]Example:
my_list = [1,2,3,4,5,6,7,8,9]
even_numbers = [x for x in my_list if x % 2 == 0]
print(even_numbers)
#Output
[2, 4, 6, 8]9. Flatten a list of lists
One Liner:
flattened_list = [item for sublist in my_list for item in sublist]Example:
my_list = [[1,2],[3,4],[5,6]]
flattened_list = [item for sublist in my_list for item in sublist]
print(flattened_list)
#Output
[1, 2, 3, 4, 5, 6]10. Find the most common element in a list
One Liner:
most_common = max(set(my_list), key=my_list.count)Example:
my_list = [1,1,1,1,1,2,2,2,3,3,3]
most_common = max(set(my_list), key=my_list.count)
print(most_common)
#Output
111. Remove duplicates from a list while preserving order
One Liner:
no_duplicates = list(dict.fromkeys(my_list))Example:
my_list = [1,1,1,1,1,3,3,3,2,2,2]
no_duplicates = list(dict.fromkeys(my_list))
print(no_duplicates)
#Output
[1, 3, 2]12. Find the least common multiple (LCM) of two numbers
One Liner:
lcm = abs(a * b) // math.gcd(a, b)Example:
import math
a = 4
b = 5
lcm = abs(a * b) // math.gcd(a, b)
print(lcm)
#Output
2013. Sort a list in reverse order
One Liner:
sorted_list = sorted(my_list, reverse=True)Example:
my_list = [1,2,3,4,5]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)
#Output
[5, 4, 3, 2, 1]14. Calculate the area of a circle
One Liner:
area_circle = math.pi * radius ** 2Example:
import math
radius = 5
area_circle = math.pi * radius ** 2
print(area_circle)
#Output
78.5398163397448315. Generate a list of prime numbers up to n
One Liner:
primes = [i for i in range(2, n) if all(i % j != 0 for j in range(2, int(i**0.5) + 1))]Example:
n = 20
primes = [i for i in range(2, n) if all(i % j != 0 for j in range(2, int(i**0.5) + 1))]
print(primes)
#Output
[2, 3, 5, 7, 11, 13, 17, 19]16. Remove vowels from a string
One Liner:
no_vowels = ''.join(c for c in my_string if c.lower() not in 'aeiou')Example:
my_string = "Logical"
no_vowels = ''.join(c for c in my_string if c.lower() not in 'aeiou')
print(no_vowels)
#Output
Lgcl17. Check if a string is a pangram
One Liner:
is_pangram = set('abcdefghijklmnopqrstuvwxyz').issubset(my_string.lower())Example:
my_string = "The quick brown fox jumps over the lazy dog"
is_pangram = set('abcdefghijklmnopqrstuvwxyz').issubset(my_string.lower())
print(is_pangram)
my_string = "The quick brown"
is_pangram = set('abcdefghijklmnopqrstuvwxyz').issubset(my_string.lower())
print(is_pangram)
#Output
True
False18. Find the longest word in a string
One Liner:
longest_word = max(my_string.split(), key=len)Example:
my_string = "Logical Python is the Best"
longest_word = max(my_string.split(), key=len)
print(longest_word)
#Output
Logical19. Count occurrences of an element in a list
One Liner:
count = my_list.count(element)Example:
my_list = [1,1,1,2,2,2,3,3]
count = my_list.count(1)
print(count)
#Output
320. Check if all elements in a list are equal
One Liner:
are_equal = all(x == my_list[0] for x in my_list)Example:
my_list = [1,1,1,2,2,2,3,3]
are_equal = all(x == my_list[0] for x in my_list)
print(are_equal)
my_list = [1,1,1,1,1]
are_equal = all(x == my_list[0] for x in my_list)
print(are_equal)
#Output
False
True21. Create a dictionary from two lists
One Liner:
is_pangram = set('abcdefghijklmnopqrstuvwxyz').issubset(my_string.lower())Example:
keys_list = [1,2,3]
values_list = ['one','two','three']
my_dict = dict(zip(keys_list, values_list))
print(my_dict)
#Output
{1: 'one', 2: 'two', 3: 'three'}22. Find unique elements in a list
One Liner:
unique_elements = list(set(my_list))Example:
my_list = [1,2,2,2,3,3,3]
unique_elements = list(set(my_list))
print(unique_elements)
#Output
[1, 2, 3]23. Check if a string is an anagram of another string
One Liner:
is_anagram = sorted(str1) == sorted(str2)Example:
str1 = "abcd"
str2 = "dcba"
is_anagram = sorted(str1) == sorted(str2)
print(is_anagram)
str1 = "abcd"
str2 = "dcbx"
is_anagram = sorted(str1) == sorted(str2)
print(is_anagram)
#Output
True
False24. Calculate the greatest common divisor (GCD) of two numbers
One Liner:
gcd = math.gcd(a, b)Example:
a = 6
b = 8
gcd = math.gcd(a, b)
print(gcd)
#Output
225. Rotate a list to the right by k steps
One Liner:
rotated_list = my_list[-k % len(my_list):] + my_list[:-k % len(my_list)]Example:
my_list = [1,2,3,4,5,6,7,8,9]
k = 3
rotated_list = my_list[-k % len(my_list):] + my_list[:-k % len(my_list)]
print(rotated_list)
#Output
[7, 8, 9, 1, 2, 3, 4, 5, 6]26. Check if a number is a perfect square
One Liner:
is_perfect_square = math.sqrt(n) ** 2 == nExample:
import math
n = 4
is_perfect_square = math.sqrt(n) ** 2 == n
print(is_perfect_square)
n = 5
is_perfect_square = math.sqrt(n) ** 2 == n
print(is_perfect_square)
#Output
True
False27. Convert a list of strings to a single string
One Liner:
single_string = ''.join(my_list)Example:
my_list = ['L', 'o', 'g', 'i', 'c', 'a', 'l']
single_string = ''.join(my_list)
print(single_string)
#Output
Logical28. Transpose a matrix
One Liner:
transposed_matrix = list(map(list, zip(*matrix)))Example:
matrix = [[1,2],
[4,5],
[6,7]]
transposed_matrix = list(map(list, zip(*matrix)))
print(transposed_matrix)
#Output
[[1, 4, 6], [2, 5, 7]]29. Reverse a string
One Liner:
reversed_string = my_string[::-1]Example:
my_string = "Logical"
reversed_string = my_string[::-1]
print(reversed_string)
#Output
lacigoL30. Check if any element in a list is true
One Liner:
any_true = any(my_list)Example:
my_list = [0,0,12,False]
any_true = any(my_list)
print(any_true)
my_list = [0,0,False,False]
any_true = any(my_list)
print(any_true)
#Output
True
False31. Find the mode of a list
One Liner:
mode = max(set(my_list), key=my_list.count)Example:
my_list = [1,1,2,2,2,3,4,4]
mode = max(set(my_list), key=my_list.count)
print(mode)
#Output
232. Find the minimum element in a list
One Liner:
min_value = min(my_list)Example:
my_list = [1,1,2,2,2,3,4,4]
min_value = min(my_list)
print(min_value)
#Output
133. Calculate the standard deviation of a list
One Liner:
standard_deviation = statistics.stdev(my_list)Example:
my_list = [1,2,3,4,5]
import statistics
standard_deviation = statistics.stdev(my_list)
print(standard_deviation)
#Output
1.581138830084189834. Check if a number is even
One Liner:
is_even = n % 2 == 0Example:
n = 5
is_even = n % 2 == 0
print(is_even)
n = 6
is_even = n % 2 == 0
print(is_even)
#Output
False
True35. Calculate the mean of a list of numbers
One Liner:
mean = sum(my_list) / len(my_list)Example:
my_list = [1,2,3,4,5]
mean = sum(my_list) / len(my_list)
print(mean)
#Output
3.036. Generate a list of random numbers
One Liner:
random_numbers = [random.randint(min_value, max_value) for _ in range(n)]Example:
n = 5
min_value = 10
max_value = 100
import random
random_numbers = [random.randint(min_value, max_value) for _ in range(n)]
print(random_numbers)
#Output
[32, 91, 60, 29, 32]37. Check if a list contains only unique elements
One Liner:
has_unique_elements = len(my_list) == len(set(my_list))Example:
my_list = [1,2,3,4,5]
has_unique_elements = len(my_list) == len(set(my_list))
print(has_unique_elements)
my_list = [1,2,3,4,5,5]
has_unique_elements = len(my_list) == len(set(my_list))
print(has_unique_elements)
#Output
True
False38. Find the longest common prefix in a list of strings
One Liner:
longest_prefix = os.path.commonprefix(strings_list)Example:
import os
strings_list = ["ab_abc","abc_abc","ab_c_abc","ab_cd_abc"]
longest_prefix = os.path.commonprefix(strings_list)
print(longest_prefix)
#Output
ab39. Calculate the sum of elements in a list
One Liner:
total = sum(my_list)Example:
my_list = [1,2,3,4,5]
total = sum(my_list)
print(total)
#Output
1540. Calculate the median of a list
One Liner:
median = sorted(my_list)[len(my_list) // 2] if len(my_list) % 2 != 0 else sum(sorted(my_list)[len(my_list) // 2 - 1:len(my_list) // 2 + 1]) / 2Example:
my_list = [1,2,3,4,5]
median = sorted(my_list)[len(my_list) // 2] if len(my_list) % 2 != 0 else sum(sorted(my_list)[len(my_list) // 2 - 1:len(my_list) // 2 + 1]) / 2
print(median)
my_list = [1,2,3,4,5,6]
median = sorted(my_list)[len(my_list) // 2] if len(my_list) % 2 != 0 else sum(sorted(my_list)[len(my_list) // 2 - 1:len(my_list) // 2 + 1]) / 2
print(median)
#Output
3
3.541. Convert a list of integers to a single integer
One Liner:
single_integer = int(''.join(map(str, my_list)))Example:
my_list = [1,2,3,4,5]
single_integer = int(''.join(map(str, my_list)))
print(single_integer)
#Output
1234542. Find the number of digits in a number
One Liner:
num_digits = len(str(number))Example:
number = 12345
num_digits = len(str(number))
print(num_digits)
#Output
543. Check if a number is a power of two
One Liner:
single_string = ''.join(my_list)Example:
n = 6
is_power_of_two = n > 0 and (n & (n - 1)) == 0
print(is_power_of_two)
n = 8
is_power_of_two = n > 0 and (n & (n - 1)) == 0
print(is_power_of_two)
#Output
False
True44. Check if a number is a palindrome
One Liner:
is_palindrome = str(n) == str(n)[::-1]Example:
n = 12321
is_palindrome = str(n) == str(n)[::-1]
print(is_palindrome)
n = 12345
is_palindrome = str(n) == str(n)[::-1]
print(is_palindrome)
#Output
True
False45. Generate a list of random unique numbers within a range
One Liner:
random_unique = random.sample(range(start, end), count)Example:
import random
start = 10
end = 100
count = 5
random_unique = random.sample(range(start, end), count)
print(random_unique)
#Output
[49, 40, 51, 71, 23]46. Remove all occurrences of a specified value from a list
One Liner:
filtered_list = [x for x in my_list if x != value_to_remove]Example:
my_list = [1,2,3,4,5,1,2,6]
value_to_remove = 1
filtered_list = [x for x in my_list if x != value_to_remove]
print(filtered_list)
#Output
[2, 3, 4, 5, 2, 6]47. Find the maximum element in a list
One Liner:
max_value = max(my_list)Example:
my_list = [1,2,3,4,6]
max_value = max(my_list)
print(max_value)
#Output
648. Generate a list of all possible permutations of a string
One Liner:
permutations = [''.join(p) for p in itertools.permutations(my_string)]Example:
import itertools
my_string = "abc"
permutations = [''.join(p) for p in itertools.permutations(my_string)]
print(permutations)
#Output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']49. Calculate the sum of the digits of a number
One Liner:
digit_sum = sum(int(digit) for digit in str(n))Example:
n = 12345
digit_sum = sum(int(digit) for digit in str(n))
print(digit_sum)
#Output
1550. Check if a number is a narcissistic number (equal to the sum of its own digits raised to the power of the number of digits)
One Liner:
is_narcissistic = n == sum(int(digit) ** len(str(n)) for digit in str(n))Example:
n = 153 #1**3 + 5**3 + 3**3 = 1+27+125
is_narcissistic = n == sum(int(digit) ** len(str(n)) for digit in str(n))
print(is_narcissistic)
n = 155
is_narcissistic = n == sum(int(digit) ** len(str(n)) for digit in str(n))
print(is_narcissistic)
#Output
True
False