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, a
Example:
a = 5
b = 10
a, b = b, a
print(a)
print(b)
#Output:
10
5
2. 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 False
3. 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
120
4. 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
False
5. 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
False
6. 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
StringwithWhiteSpaces
8. 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
1
11. 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
20
13. 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 ** 2
Example:
import math
radius = 5
area_circle = math.pi * radius ** 2
print(area_circle)
#Output
78.53981633974483
15. 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
Lgcl
17. 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
False
18. 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
Logical
19. 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
3
20. 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
True
21. 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
False
24. 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
2
25. 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 == n
Example:
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
False
27. 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
Logical
28. 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
lacigoL
30. 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
False
31. 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
2
32. 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
1
33. 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.5811388300841898
34. Check if a number is even
One Liner:
is_even = n % 2 == 0
Example:
n = 5
is_even = n % 2 == 0
print(is_even)
n = 6
is_even = n % 2 == 0
print(is_even)
#Output
False
True
35. 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.0
36. 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
False
38. 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
ab
39. 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
15
40. 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]) / 2
Example:
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.5
41. 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
12345
42. 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
5
43. 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
True
44. 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
False
45. 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
6
48. 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
15
50. 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