5 More Python One-liners You Should Use | by Tate Galbraith | Mar, 2022

Photo by Luke Peters on Unsplash

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.

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 “_suffixto 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 clean things up.

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.

Let’s try the name example. Let’s assume we have the following list of full names:

name_list = ['Kathy Bates', 'George Clooney', 'Will Smith']

Now, let’s assume we wanted to determine if anyone named “George” is in our list:

any('George' in name for name in name_list)

Short and sweet. Using any with a simple in check allows us to quickly determine if any of the elements contain the name “George”.

Obviously, if you were to run this code you’d get the following result:


Now we know where George Clooney is hiding.

When you’re working with destructuring assignments it can be tricky to have other elements in the list that you don’t need to assign. These elements generally pop up at the end of lists, but sometimes they appear at the beginning or in the middle. This presents an annoying problem of having to drop some variables during destructuring assignments.

Luckily there is an easy way to drop unused variables when assigning them. Let’s take the data below:

person = ['bob', 'smith', 39, 'professor']

In this data, we have information about a person. We have a first name, last name, age, and profession. Let’s say we want to destructure this into individual variables, but we don’t really care about Bob’s last name or his age (Bob is eternal):

first_name, *_, profession = person

Using the magic *_ syntax we can omit several elements in a row except for the remaining one. If we print out each variable we can see we now have the proper data:

>>> bob
>>> professor

If we wanted to simply omit one element instead of many we could use _. This would skip the next positional element in the list as we consume it.

This is a pretty common programming task. Whether you’re getting data back from a database or sanitizing some user-supplied information, removing duplicates is an all too common housekeeping task.

Suppose you have a list of numbers and you’d like to ensure it doesn’t contain any duplicates:

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

The simplest and cleanest way to make a list unique is to convert it to a set. A set It doesn’t allow duplicated values ​​by default, so your list will automatically become unique simply by converting it. Don’t worry, you can convert it back to a list right after:

unique_list = list(set(my_numbers))

Now if we print out our unique_list variable we’ll see only the unique values:

>>> [1, 2, 3, 4, 5, 6, 7, 8]

Have you ever been writing a lengthy script or manipulating a large, complicated data set and wound up with a ton of import statements? Near the top of your file, it looks like an ocean of import import import. It’s like they put the credits for a movie at the beginning. Just take me to the good part already.

If you’re swimming in an import city then you might be wondering how to reduce the total number of statements. One method might be to chop up your files a bit more and make them more modular. This is an option, but sometimes breaking things up leads to unnecessary duplication and even increased complexity. Sometimes it is nice (and potentially more readable) to have it all in one place.

An alternative method is to use the pyforest module. This is a third-party module that allows you to write a single line import statement and have it dynamically import many other boilerplate modules on the fly.

import pyforest

That’s all it takes to pull in a dump truck full of modules. The best part is you’re not actually pulling them in… yet. The pyforest module will only import something when you reference it. So if you wanted to reference the os module (and many others), all you have to do is import pyforest and then use os in any capacity following the import statement.

import pyforestos.getpid()

If you run the code above you’ll be presented with a successful run and the process ID of your current Python instance.

This module is incredibly useful for reducing clutter, dynamically loading modules, and reducing the overall startup time of your code.

Check out the official pyforest GitHub for more info:

Leave a Comment