DEV Community

Cover image for 20 Python One-Liners That Will Surprise You
Shefali
Shefali

Posted on • Originally published at shefali.dev

20 Python One-Liners That Will Surprise You

Python is known for its simple and readable syntax.

But some Python one-liners make things even easier. Tasks that usually take several lines of code can sometimes be done in just one line.

In this post, I’ll share 20 useful Python one-liners that show just how simple and powerful Python can be.

Let’s jump right into it! 🚀

1. Swap Two Variables

You can swap the values of two variables in just one line. There’s no need to create a temporary variable.

a, b = 5, 10

a, b = b, a

print(a, b)  # 10 5
Enter fullscreen mode Exit fullscreen mode

Python uses tuple unpacking to swap the values. It’s a simple and clean way to exchange values between two variables.

Swap Two Variables in Python

2. Reverse a List or String

You can reverse a list or string using [::-1].

nums = [1, 2, 3, 4, 5]

print(nums[::-1])  # [5, 4, 3, 2, 1]

print("hello"[::-1])  # "olleh"
Enter fullscreen mode Exit fullscreen mode

The [::-1] slice reads the sequence from the end to the beginning. It works with lists, strings, and tuples, so you don’t need a loop.

Reverse a List or String in Python

3. Flatten a Nested List

You can turn a nested list into a single list using a list comprehension.

nested = [[1, 2], [3, 4], [5, 6]]

flat = [x for sublist in nested for x in sublist]

print(flat)  # [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

The code goes through each sublist and adds every item x to the new list.

It may look a little confusing at first, but it’s a short and useful way to flatten a list with one level of nesting.

Flatten a Nested List - Python one-liners

4. Count Occurrences in a List

You can use Counter to quickly count how many times each item appears in a list.

from collections import Counter

words = ["python", "css", "python", "js", "css", "python"]

print(Counter(words))

# Counter({'python': 3, 'css': 2, 'js': 1})
Enter fullscreen mode Exit fullscreen mode

Counter automatically counts each item and shows how many times it appears. You don’t need to write a loop or create a dictionary manually.

Count Occurrences in a List - Python one-liners

5. Remove Duplicates While Preserving Order

You can remove duplicate items from a list while keeping the original order using dict.fromkeys().

items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]

unique = list(dict.fromkeys(items))

print(unique)  # [3, 1, 4, 5, 9, 2, 6]
Enter fullscreen mode Exit fullscreen mode

Using set() also removes duplicates, but it doesn’t guarantee the original order. dict.fromkeys() keeps the items in the same order they first appeared.

Remove Duplicates While Preserving Order - Python one-liners

6. Merge Two Dictionaries

You can combine two dictionaries into one using the ** unpacking operator.

a = {"name": "Shefali", "role": "developer"}

b = {"country": "India", "role": "writer"}

merged = {**a, **b}

print(merged)

# {'name': 'Shefali', 'role': 'writer', 'country': 'India'}
Enter fullscreen mode Exit fullscreen mode

The ** operator unpacks both dictionaries and combines their items. If the same key exists in both dictionaries, the value from the second dictionary is used.

Merge Two Dictionaries- Python one-liners

7. Find the Most Frequent Element

You can find the item that appears most often in a list using max().

nums = [1, 3, 2, 3, 4, 3, 5]

most_common = max(set(nums), key=nums.count)

print(most_common)  # 3
Enter fullscreen mode Exit fullscreen mode

set(nums) gets the unique values, and nums.count counts how many times each value appears. max() then returns the value with the highest count.

Find the Most Frequent Element- Python one-liners

8. Check if a String is a Palindrome

A palindrome is a word that reads the same forward and backward, like "racecar".

word = "racecar"

is_palindrome = word == word[::-1]

print(is_palindrome)  # True
Enter fullscreen mode Exit fullscreen mode

This code reverses the word using [::-1] and compares it with the original word. If both are the same, the word is a palindrome.

Check if a String is a Palindrome- Python one-liners

9. Generate a List of Squares

You can create a list of squares using a list comprehension.

squares = [x**2 for x in range(1, 11)]
print(squares)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Enter fullscreen mode Exit fullscreen mode

The code goes through numbers from 1 to 10, squares each number, and adds the result to a new list.

Generate a List of Squares - Python one-liners

10. Read a File Into a List of Lines

You can read all the lines from a file and store them in a list in one line.

lines = open("file.txt").read().splitlines()
Enter fullscreen mode Exit fullscreen mode

read() reads the file content, and splitlines() splits it into separate lines without keeping the newline characters.

Read a File Into a List of Lines - Python one-liners

11. Transpose a Matrix

You can swap the rows and columns of a matrix using zip().

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

transposed = list(map(list, zip(*matrix)))

print(transposed)

# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Enter fullscreen mode Exit fullscreen mode

zip(*matrix) groups the values from each column together. map(list, ...) then converts each group into a list.

The result turns the rows of the original matrix into columns.

Transpose a Matrix

12. Filter a List by Condition

You can use filter() to keep only the items that match a condition.

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

evens = list(filter(lambda x: x % 2 == 0, nums))

print(evens)  # [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

The lambda checks if each number is even. filter() keeps only the numbers that pass this condition.

You can also write the same code using a list comprehension:

evens = [x for x in nums if x % 2 == 0]
Enter fullscreen mode Exit fullscreen mode

Filter a List by Condition

13. Sort a List of Dictionaries by Key

You can sort a list of dictionaries based on a specific value using sorted().

people = [ 

    {"name": "Alice", "age": 30}, 

    {"name": "Bob", "age": 25}, 

    {"name": "Carol", "age": 35} 

] 

sorted_people = sorted(people, key=lambda x: x["age"]) 

print(sorted_people) 


# [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Carol', 'age': 35}]
Enter fullscreen mode Exit fullscreen mode

Here, the lambda tells sorted() to use the age value when sorting. The result is a list sorted from the youngest person to the oldest.

Sort a List of Dictionaries by Key

14. Create a Dictionary from Two Lists

You can combine two lists to create a dictionary using zip() and dict().

keys = ["name", "age", "country"]

values = ["Shefali", 27, "India"]

result = dict(zip(keys, values))

print(result)

# {'name': 'Shefali', 'age': 27, 'country': 'India'}
Enter fullscreen mode Exit fullscreen mode

zip() pairs each item from the keys list with an item from the values list. dict() then turns these pairs into a dictionary.

Create a Dictionary from Two Lists

15. Find Items Unique to One List

You can use sets to find items that exist in one list but not in another.

a = [1, 2, 3, 4, 5]

b = [3, 4, 5, 6, 7]

unique_to_a = list(set(a) - set(b))

print(unique_to_a)  # [1, 2]
Enter fullscreen mode Exit fullscreen mode

The - operator finds the difference between two sets. In this example, it returns the items that are in a but not in b.

You can also use & to find common items and | to combine items from both sets.

Find Items Unique to One List

16. Find All Indices of an Element

You can find every position where an item appears using enumerate().

nums = [10, 20, 30, 20, 40, 20]

indices = [i for i, x in enumerate(nums) if x == 20]

print(indices)  # [1, 3, 5]
Enter fullscreen mode Exit fullscreen mode

enumerate() gives you both the index and value of each item. The condition then keeps only the indices where the value is 20.

Find All Indices of an Element

17. Ternary Expression

You can write a simple if-else condition in one line using a ternary expression.

age = 20

label = "adult" if age >= 18 else "minor"

print(label)  # "adult"
Enter fullscreen mode Exit fullscreen mode

If age is 18 or more, label becomes "adult". Otherwise, it becomes "minor".

This is useful for short and simple conditions.

Ternary Expression

18. Repeat a String or List

You can use the * operator to repeat a string or list.

print("ha" * 3)        # "hahaha"

print([0] * 5)         # [0, 0, 0, 0, 0]
Enter fullscreen mode Exit fullscreen mode

Multiplying a string repeats its text, while multiplying a list repeats its items.

This is a quick way to create repeated values.

Repeat a String or List

19. Unpack a List Into First and Rest

You can store the first item separately and collect the remaining items in another variable.

first, *rest = [1, 2, 3, 4, 5]

print(first)  # 1

print(rest)   # [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

The *rest variable collects all the remaining items into a list.

You can also use *init, last if you want to store the last item separately.

Unpack a List Into First and Rest

20. Print a Multiplication Table

You can create a complete 10×10 multiplication table in one line.

print('\n'.join(['\t'.join([str(x*y) for x in range(1, 11)]) for y in range(1, 11)]))
Enter fullscreen mode Exit fullscreen mode

The inner list comprehension multiplies the numbers in each row. '\t'.join() separates the values with tabs, while '\n'.join() puts each row on a new line.

It’s a compact way to generate an entire multiplication table with one line of Python.

Print a Multiplication Table


That’s all for today!

I hope you found these Python one-liners useful and learned a few new tricks.

For paid collaboration, connect with me at: connect@shefali.dev

If you enjoy my work and want to support what I do buy me a coffee!

Every small gesture keeps me going! 💛

Follow me on X (Twitter) to get daily web development tips & insights.


Enjoyed reading? You may also find these articles helpful.

Python Libraries Every Developer Should Know

Explore 16 useful Python libraries every developer should know about, from APIs and automation to data science and web development.

favicon shefali.dev

Python Roadmap: Learn Step by Step

A complete Python roadmap for beginners, covering basics to advanced concepts in a clear, step-by-step learning order.

favicon shefali.dev

Top comments (0)