Unlocking the Magic of Python One-Liners: Essential Functions for Efficient Code Writing

Avi Rzayev
7 min readJul 13, 2023

Python is a versatile programming language known for its readability and expressiveness. While it encourages writing clean and maintainable code, there are instances where concise one-liners can save time and effort. In this article, we will explore the art of writing Python one-liners.

List Comprehension:

Python’s list comprehension offers a concise and powerful way to create lists. It allows you to combine loops and conditional statements into a single line of code. Let’s take a closer look at how list comprehension works.

Let’s observe this piece of code that separates even numbers into a new list:

random_numbers = [1, 3, 2, 8, 11, 20, 10]
even_numbers = []

for number in random_numbers:
if number % 2 == 0:
even_numbers.append(number)

print(even_numbers)
# Output: [2, 8, 20, 10]
random_numbers = [1, 3, 2, 8, 11, 20, 10]
even_numbers = [number for number in random_numbers if number % 2 == 0]

print(even_numbers)
# Output: [2, 8, 20, 10]

This code looks simple but we can make it simpler by using for loop when initializing our list:

random_numbers = [1, 3, 2, 8, 11, 20, 10]
even_numbers = [number for number in random_numbers if number % 2 == 0]

print(even_numbers)
# Output: [2, 8, 20, 10]

Now the code looks shorter and is still possible to understand! If you struggle to understand how to use List Comprehension here is a template for you:

my_list = [<final_result> for <list_element> in <iterator> <if <some condition>>]

Note that you can also create lists without using the if statements:

square_numbers = [number ** 2 for number in random_numbers]

List Comprehension also applies to dictionaries and sets:

random_numbers = [1, 3, 2, 8, 11, 20, 10]

even_numbers = set(number for number in random_numbers if number % 2 == 0)
print(even_numbers)
# Output: {2, 8, 20, 10}

square_numbers = {number: number ** 2 for number in random_numbers}
print(square_numbers)
# Output: {1: 1, 3: 9, 2: 4, 8: 64, 11: 121, 20: 400, 10: 100}

map() & filter() Functions:

There are cases where you what to run a function over all the elements in a list.

For instance, if we what to round the numbers in our list, we can do that by using List Comprehension:

float_numbers = [1.3, 3.2, 10.4, 9.432, 342.2]
rounded_numbers = [round(number) for number in float_numbers]

print(rounded_numbers)
# Output: [1, 3, 10, 9, 342]

Now here is the magic begins! We can use the map() function to shorten our code even more.

map() is a built-in function that applies a given function to each item of an iterable (such as a list, tuple, or string) and returns an iterator with the results. The general syntax of the map() function is as follows:

map(function, iterable)

So now our code can look like this:

float_numbers = [1.3, 3.2, 10.4, 9.432, 342.2]
rounded_numbers = list(map(round, float_numbers))

print(rounded_numbers)
# Output: [1, 3, 10, 9, 342]

Remember we wanted to filter out our even numbers? We can use filter() to achieve the same thing!

filter() is a built-in function that allows you to selectively filter elements from an iterable based on a given condition. It returns an iterator containing the elements from the original iterable that satisfy the specified condition.

The general syntax of the filter() function is as follows:

filter(function, iterable)

So now the code can look like this:

def is_even(number):
return number % 2 == 0

random_numbers = [1, 3, 2, 8, 11, 20, 10]
even_numbers = list(filter(is_even, random_numbers))

print(even_numbers)
# Output: [2, 8, 20, 10]

map() and filter() can also be combined together. Sometimes the combination simplifies the code and sometimes it doesn’t. Don’t force it if it makes the code difficult to understand.

Here is an example of rounding the numbers and selecting only the even ones using map() and filter():

def is_even(number):
return number % 2 == 0

float_numbers = [1.3, 3.2, 10.4, 9.432, 342.2]

rounded_numbers = list(filter(is_even, map(round, float_numbers)))

print(rounded_numbers)
# Output: [10, 342]

And here is the same implementation if we stick to List Comprehension:

float_numbers = [1.3, 3.2, 10.4, 9.432, 342.2]

rounded_numbers = [round(number) for number in float_numbers if round(number) % 2 == 0]

print(rounded_numbers)
# Output: [10, 342]

map() and filter() are making the line shorter but List Comprehension may make it more easier to understand. It’s up to you to choose what is more convenient for you.

Lambda Functions

Remember we created this function to pass into the filter() method?

def is_even(number):
return number % 2 == 0

The usage of filter() made us write more lines, our goal was to write everything in one line. Here come lambdas to solve this problem.

Lambda functions are anonymous functions that can be defined in a single line. They are useful when a small, throwaway function is required.

The syntax of lambda is:

lambda arguments: output expression

Here is an example:

is_even = lambda number: number % 2 == 0

print(is_even(3))
# Output: False

print(is_even(6))
# Output: True

So if we apply this to our original example of filtering even numbers from a list our code will look like this:

random_numbers = [1, 3, 2, 8, 11, 20, 10]
even_numbers = list(filter(lambda number: number % 2 == 0, random_numbers))

print(even_numbers)
# Output: [2, 8, 20, 10]

zip() Function

The zip() function allows you to iterate over multiple iterables simultaneously. It combines corresponding elements from each iterable into tuples.

Here’s an example that demonstrates the usage of zip() to combine two lists into a list of tuples:

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

zipped = list(zip(names, ages))

print(zipped)
# Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

any() and all() Functions

The any() and all() functions are useful for checking conditions on multiple values. any() returns True if any element in an iterable evaluates to True. all() returns True only if all elements evaluate to True

Consider this example that checks if any number in a list is divisible by 5:

random_numbers = [7, 13, 20, 42, 8]
is_divisible_by_5 = any(x % 5 == 0 for x in random_numbers)

print(is_divisible_by_5)
# Output: True

functools.reduce()

The reduce() function from the functools module applies a function of two arguments cumulatively to the elements of an iterable. It returns a single value as the result.

Here's an example that calculates the product of a list of numbers, instead of doing this:

random_numbers = [2, 3, 4, 5]
product = 1

for num in random_numbers:
product *= num

print(product)
# Output: 120

You can do this (notice how we used lambda here):

from functools import reduce

random_numbers= [2, 3, 4, 5]
product = reduce(lambda x, y: x * y, random_numbers)

print(product)
# Output: 120

itertools module

itertools is a module in the standard library that provides a collection of functions for creating and manipulating iterators. Iterators are objects used to traverse over a collection of elements one at a time, without the need to store the entire collection in memory.

The itertools module offers several functions that generate iterators based on common combinatorial patterns. These functions are designed to efficiently generate elements on-the-fly, making them memory-efficient and suitable for working with large or infinite sequences.

repeat() Function

The repeat() function generates an iterator that repeatedly returns the same element a specified number of times, or indefinitely if times is not provided.

Syntax:

repeat(element, times=None)

Here is a simple example:

import itertools

repeated = list(itertools.repeat('Hello', 3))

print(repeated)
# Output: ['Hello', 'Hello', 'Hello']

combinations() Function

The combinations() function generates an iterator that yields all possible combinations of length r from the elements of the iterable.

Syntax:

combinations(iterable, r)

For example:

import itertools

letters = ['A', 'B', 'C']
combinations = list(itertools.combinations(letters, 2))

print(combinations)
# Output: [('A', 'B'), ('A', 'C'), ('B', 'C')]

permutations() Function

A permutation is an arrangement of elements in a specific order.

The permutations() function generates an iterator that yields all possible permutations of length r from the elements of the iterable. If r is not provided, it generates all possible permutations of the entire iterable.

Syntax:

permutations(iterable, r=None)

Here is an example code:

import itertools

letters = ['A', 'B', 'C']
permutations = list(itertools.permutations(letters))

print(permutations)
# Output: [('A', 'B', 'C'),
# ('A', 'C', 'B'),
# ('B', 'A', 'C'),
# ('B', 'C', 'A'),
# ('C', 'A', 'B'),
# ('C', 'B', 'A')]

chain() Function

My favorite function. The chain() function combines multiple iterables into a single iterator, sequentially yielding elements from each iterable in the order they are passed.

Syntax:

chain(*iterables)

Here is a common example that flattens a list of lists:

import itertools

lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flatten = list(itertools.chain(*lists))

print(flatten)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

One-liners are good but don’t abuse them

While one-liners in Python can be concise and efficient in certain situations, it’s important to consider readability, maintainability, and code clarity when deciding whether to use them.

Here is a one-liner that I wrote at work and my team almost beat me up because of it:

import itertools

categories = {"Vegetables": ["Tomato", "Cucumber", "Onion"], "Fruits": ["Banana", "Apple"]}

flatten_categories = list(itertools.chain(*[list(zip([category] * len(items), items)) for category, items in categories.items()]))

print(flatten_categories)
# Output:
# [('Vegetables', 'Tomato'),
# ('Vegetables', 'Cucumber'),
# ('Vegetables', 'Onion'),
# ('Fruits', 'Banana'),
# ('Fruits', 'Apple')]

The code should flatten a dictionary of lists to pairs of keys and list elements. It is not readable. This one-liner is worth nothing. It is better to separate it into multiple lines like this:

categories = {"Vegetables": ["Tomato", "Cucumber", "Onion"], "Fruits": ["Banana", "Apple"]}

flatten_categories = []

for category, items in categories.items():
flatten_categories += [(category, item) for item in items]

# Output:
# [('Vegetables', 'Tomato'),
# ('Vegetables', 'Cucumber'),
# ('Vegetables', 'Onion'),
# ('Fruits', 'Banana'),
# ('Fruits', 'Apple')]

Conclusion

Python one-liners can be powerful tools for concise and efficient code. They offer a way to express ideas succinctly and perform operations in a single line. However, it’s important to exercise caution when using one-liners. Prioritizing code readability, maintainability, and collaboration with other developers should be paramount. One-liners should not sacrifice clarity for brevity, and complex logic or nested expressions may be better served by more explicit code structures. Remember, striking a balance between brevity and readability is key to producing code that is not only efficient but also understandable and maintainable in the long run.

--

--