Python One-Liners – The Ultimate Collection

This resource is meant to be the ultimate collection of Python One-Liners. If you have an idea for a one-liner to be published here, send me a message at chris (at)

Find All Indices of an Element in a List

Say, you want to do the same as the list.index(element) method but return all indices of the element in the list rather than only a single one.

In this one-liner, you’re looking for element 'Alice' in the list [1, 2, 3] so it even works if the element is not in the list (unlike the list.index() method).

lst = [1, 2, 3]
indices = [i for i in range(len(lst)) if lst[i]=='Alice']
index = indices[0] if indices else None

Load a File into a List Line By Line

Say, you want to load all lines of a given file 'chat.txt' into a new list. You can use the following one-liner to do it for you in the most concise way.

lst = [line for line in open('chat.txt')]

Python Sum List of Tuples Element Wise

Problem: How to sum up a list of tuples, element-wise?

Example: Say, you’ve got list [(1, 1), (2, 0), (0, 3)] and you want to sum up the first and the second tuple values to obtain the “summed tuple” (1+2+0, 1+0+3)=(3, 4).

Solution: Unpack the tuples into the zip function to combine the first and second tuple values. Then, sum up those values separately. Here’s the code:

# list of tuples
lst = [(1, 1), (2, 0), (0, 3)]

# aggregate first and second tuple values
zipped = list(zip(*lst))
# result: [(1, 2, 0), (1, 0, 3)]

# calculate sum of first and second tuple values
res = (sum(zipped[0]), sum(zipped[1]))

# print result to the shell
# result: (3, 4)

Need a refresher of the zip() function and unpacking? Check out these articles on the Finxter blog:

Find Pairs of Matchings in a List

Suppose you want to use list comprehension to make this code more concise (for example, you want to find all possible pairs of users in your social network application):

users = ["John", "Alice", "Ann", "Zach"]
pairs = []
for x in users:
    for y in users:
        if x != y:
#[('John', 'Alice'), ('John', 'Ann'), ('John', 'Zach'), ('Alice', 'John'), ('Alice', 'Ann'), ('Alice', 'Zach'), ('Ann', 'John'), ('Ann', 'Alice'), ('Ann', 'Zach'), ('Zach', 'John'), ('Zach', 'Alice'), ('Zach', 'Ann')]

Now, this code is a mess! How can we fix it? Simply use nested list comprehension!

pairs = [(x,y) for x in users for y in users if x!=y]
# [('John', 'Alice'), ('John', 'Ann'), ('John', 'Zach'), ('Alice', 'John'), ('Alice', 'Ann'), ('Alice', 'Zach'), ('Ann', 'John'), ('Ann', 'Alice'), ('Ann', 'Zach'), ('Zach', 'John'), ('Zach', 'Alice'), ('Zach', 'Ann')]

As you can see, we are doing exactly the same thing as with un-nested list comprehension. The only difference is to write the two for loops and the if statement in a single line within the list notation [].

How to Calculate the Column Average of a List of Lists in Python?

A simple one-liner with list comprehension in combination with the zip() function on the unpacked list to transpose the list of lists does the job in Python.

data = [[0, 1, 0],
        [1, 1, 1],
        [0, 0, 0],
        [1, 1, 0]]

# Method 1: Pure Python
res = [sum(x) / len(x) for x in zip(*data)]
# [0.5, 0.75, 0.25]

How to Filter Dictionary By Key

Here’s how you can filter a dictionary by key using only a single line of code (without defining your custom filter function as in method 2):

names = {1: 'Alice',
         2: 'Bob',
         3: 'Carl',
         4: 'Ann',
         5: 'Liz'}

print(dict(filter(lambda x: x[0]%2 == 1, names.items())))
# {1: 'Alice', 3: 'Carl', 5: 'Liz'}

You may recognize the same filter lambda function lambda x: x[0]%2 == 1 that returns True if the key is an odd integer. Note that this lambda function takes only a single input as this is how the filter() function works (it requires that you pass a function object that takes one argument and maps it to a Boolean value).

You operate on the iterable names.items() that gives you all (key, value) pairs (an element of the iterable is a (key, value) tuple).

After filtering, you convert the filter object back to a dictionary using the dict(...) constructor function.

Another example:

print(dict(filter(lambda x: x[0]%2 == 0, names.items())))
# {2: 'Bob', 4: 'Ann'}

Book Python One-Liners

Do you love Python one-liners? I do for sure—I’ve even written a whole book about it with San Francisco Publisher NoStarch. Click to check out the book in a new tab:

Python One-Liners Book

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!