I’ve written Python for about three years now, and one-liners still surprise me with how much they can do. Here’s a collection of the ones I like best, useful whether you’re new to the language or have been at it a while.
- Reverse a String:
reversed_string = "Hello World"[::-1]- Check if a Number is Even:
is_even = lambda x: x % 2 == 0- Find the Intersection of Two Lists:
intersection = list(set(list1) & set(list2))- Remove Duplicates from a List:
no_duplicates = list(set(my_list))- Calculate the Length of a String without Using len():
length = sum(1 for _ in 'Hello World')- Check if a List Contains All Elements of Another List:
contains_all = all(elem in list1 for elem in list2)- Generate a String of Random Characters:
import random;
random_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10))- Convert a List of Integers to a Single Number:
num = int(''.join(map(str, [1, 2, 3, 4, 5])))- Palindromic Check:
is_palindrome = lambda s: s == s[::-1]- List Flattening:
flatten_list = sum([[1, 2], [3, 4]], [])- Find the Most Frequent Element in a List:
most_frequent = max(set(my_list), key=my_list.count)- Merge Two Dictionaries:
merged_dict = {**dict1, **dict2}If you have feedback, leave a comment below, or send me an email. I’d love to see your favorite Python one-liners too.
If you’re interested in advancing your programming skills and would love to learn how to build cool projects like Docker, BitTorrent, or even understand the internals of your favorite tools such as Git, grep and etc by recreating them in your preferred programming language, I highly recommend you join Code Crafters.
If you loved this post, you can always support my work by buying me a coffee. Your support would mean the world to me! Also, if you end up sharing this on X, definitely tag me @muhammad_o7. Also follow me on LinkedIn
Want new posts in your inbox? Subscribe by email or follow the RSS feed.