Member-only story
5 More Python One-liners You Should Use
Solve problems. Save time. Go fast

Welcome back to another edition of:
“Look at how much cool stuff this short bit of code can do!”
In this installment, we’ll be exploring some really cool sections of Python code. These short one-liners solve a wide range of problems and can get you out of a jam if you’ve managed to program yourself into a corner.
Some of these examples are from the Python standard library, while others are from third-party libraries. The next time you need a quick fix, want to save time or just want to make something look a bit more concise, give these a try.
1. Mapping lists with lambdas
Our first example is one of the most useful, but also quite controversial. This one-liner allows you to iterate over the contents of a list and then perform actions on the individual elements inside it. The list can easily be altered in place, creating a modified version and saving you from a classic for
or while
loop.
Below is an example of mapping over a list of strings and adding the phrase “_suffix” to the end of each one:
original_list = ['one', 'two', 'three']new_list = list(map(lambda x: str(x) + '_suffix', original_list))
After running this, our new_list
variable should contain the following:
['one_suffix', 'two_suffix', 'three_suffix']
The reason that using this compact method is controversial is that with larger lambda expressions it can become much less readable than a traditional multi-line loop. The lambda function can become messy and you can begin to obfuscate intent in the code. Using this for complex list operations is ill-advised, but quick changes like this can dramatically clean things up.
2. Checking if a string is contained within a list of strings
This is one bit of code that I have come back to countless times. The usefulness of being able to know if something is contained within any items of a list is super handy. This can easily be used for locating a version number or finding a name in a list of names.