python

One Liners Python Edition

Twelve Python one-liners I use often: reverse a string, dedupe a list, flatten nested lists, merge dictionaries, find the most common item, and more.

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.

  1. Reverse a String:
python
reversed_string = "Hello World"[::-1]
  1. Check if a Number is Even:
python
is_even = lambda x: x % 2 == 0
  1. Find the Intersection of Two Lists:
python
intersection = list(set(list1) & set(list2))
  1. Remove Duplicates from a List:
python
no_duplicates = list(set(my_list))
  1. Calculate the Length of a String without Using len():
python
length = sum(1 for _ in 'Hello World')
  1. Check if a List Contains All Elements of Another List:
python
contains_all = all(elem in list1 for elem in list2)
  1. Generate a String of Random Characters:
python
import random; 
random_str = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10))
  1. Convert a List of Integers to a Single Number:
python
num = int(''.join(map(str, [1, 2, 3, 4, 5])))
  1. Palindromic Check:
python
is_palindrome = lambda s: s == s[::-1]
  1. List Flattening:
python
flatten_list = sum([[1, 2], [3, 4]], [])
  1. Find the Most Frequent Element in a List:
python
most_frequent = max(set(my_list), key=my_list.count)
  1. Merge Two Dictionaries:
python
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.