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 to chris (at) finxter.com.
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 print(index)
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 print(res) # 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):
# BEFORE users = ["John", "Alice", "Ann", "Zach"] pairs = [] for x in users: for y in users: if x != y: pairs.append((x,y)) print(pairs) #[('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!
# AFTER pairs = [(x,y) for x in users for y in users if x!=y] print(pairs) # [('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)] print(res) # [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'}
Coding Challenge Hashtag Generator
This was posed in a programming challenge:
The marketing team is spending way too much time typing in hashtags.
Let’s help them with our own Hashtag Generator!
Here’s the deal:
- It must start with a hashtag (
#
). - All words must have their first letter capitalized.
- If the final result is longer than 140 chars it must return
false
. - If the input or the result is an empty string it must return
false
.
Here are some examples:
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata" " Hello World " => "#HelloWorld" "" => False
Solution 1 by Hrishiii:
# Solution 1 def generate_hashtag(s): return "#" + s.strip().title().translate(s.strip().maketrans("",""," ")) if 0<len(s)<141 else False
Solution 2 (even more concise) by Hrishiii‘s friend:
# Solution 2 generate_hashtag = lambda d:(lambda b:d>''<b==b[:139]and'#'+b)(d.title().replace(' ',''))
Let’s explain this code next!
This creates a function object that takes one argument d
and returns the hashtag version. It assigns this function to variable generate_hashtag
. The function “body” consists of two parts:
(lambda b:d>''<b==b[:139]and'#'+b)
(d.title().replace(' ',''))
The first part creates a new function object and the second part calls it on the empty-space-removed title. The latter is in parentheses and it’s passed into the function created in the first part (assigned to function argument b
). So, let’s understand this function body:
d>''<b==b[:139] and '#'+b
You must know that x > y < z == a
is the same as x > y and y < z and z == a
.
Now, you can break it into a series of “and” operators: https://blog.finxter.com/python-and-operator/
The trick is that the “and” operator returns the second operand if the first operand is True
, otherwise it returns the first operand. It works on strings too! So, 'hello' and 'finxter'
returns 'finxter'
.
Okay, I hope these are useful for you so you can figure the rest out by yourself (again, the variable "b"
in the function body takes the result of the expression ” d.title().replace(' ','')
” that was the input into the inner function.
Finxter Hrishiii’s friend really is a one-liner genius!!
ROT13 Algorithm
Check out the ROT13 algorithm in our blog article. Finxter Higrm found a nice one-liner solution:
def rot13(phrase): abc = "abcdefghijklmnopqrstuvwxyz" out_phrase = '' for char in phrase: out_phrase += abc[(abc.find(char)+13)%26] return out_phrase def rot1Liner(phrase): return "".join([(chr((ord(char)-84)%26 + 97)) for char in phrase]) x = "xthexrussiansxarexcoming" print(rot13(x)) print(rot1Liner(x)) print(rot1Liner(rot1Liner(x)))
Power of 2
Here’s another one-liner that checks whether integer N is a power of 2:
N = 32 print(1 == bin(N).count("1")) # True
This works also when N is 0 (zero). This one-liner was contributed by Finxter Yehuda.
Even Values in an Array
Finxter Hrishiii contributed the following problem:
“Write a small function that returns the values of an array that are not odd. All values in the array will be integers. Return the good values in the order they are given.“
He provides the following three one-liners that are all supposed to solve the problem:
#no_odds= lambda values:list(filter(lambda x: not x%2, values)) #no_odds=lambda values:[*filter(lambda x: not x%2, values)] #no_odds = lambda v: list(filter(lambda i:i&1^1,v))
Thanks for the contribution! 🙂
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:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.