Image by Author | Ideogram
Â
Python one-liners are, as the post title suggests, game-changing solutions to make your code more compact and efficient, typically by simplifying a process that often requires multiple lines of code into a single one. This article lists 10 efficient examples of one-liners that, despite their simplicity, can significantly enhance your coding tasks by simplifying and streamlining common operations and repetitive tasks needed frequently.
Let’s get right into it.
Â
1. Lambda Functions
Â
Arguably one of the most well-known one-liners, lambda functions is a very compact approach to defining anonymous functions by simply specifying input arguments on the left-hand side of a “:” sign, and what you want to do to them on the right side. This code defines a function to calculate a discounted price by reducing an original product’s price by 10%.
price_after_discount = lambda price: price*0.9
Â
2. Map Operations on Lists
Â
Map operations are extremely useful for applying the same transformation to all elements in a collection like lists. They can be also used in combination with custom reusable lambda functions. For instance, suppose you have a list of original product prices in a tourist souvenir store subject to tax-free policy, and you want another list with the final price after tax deduction (10%) of the total price. By using the previously defined lambda function, can try something like:
discounted_prices = list(map(price_after_discount, prices))
Â
3. Unpacking Lists
Â
Suppose you have a price list like product_prices = [19.99, 5.49, 12.99]
, and you want to print all these prices one by one. Instead of doing this with a loop structure, why not use the ‘*’ operator to unpack the list and print its elements separated by white spaces in a single line?
Â
4. List Comprehension with a Condition
Â
You have a list of product names in your shop, like products = ["Keychain", "T-Shirt", "Mug", "Magnet", "Snow Globe"]
, and you want to obtain a new list containing the indices of products whose name starts with ‘M’. You can do this through list comprehension, that is, building a new list based on analyzing a condition in the values of an existing list.
[index for index in range(len(products)) if products[index][0] == 'M']
Â
5. Checking Conditions Efficiently with any
and all
Â
A useful pair of functions to quickly check a condition in all elements in a collection, are any and all. Both of them return a True/False value, indicating whether at least one element holds the condition (any), or whether all elements in the collection accomplish it (all).
If you have a list of inventory levels for your products, like inventory = [4, 0, 7, 10, 0]
, you can try:
any_out_of_stock = any(stock == 0 for stock in inventory)
all_in_stock = all(stock > 0 for stock in inventory)
Â
6. Walrus Operator for Faster Condition Checking
Â
The Walrus operator ‘:=’ combines assignment and use of a variable within the same expression, thereby simplifying the approach to perform conditional statements where we need a single-use variable. For example, assuming we are analyzing a customer text review before being submitted, an efficient way to check that the review has at least 30 characters is:
if (n := len(customer_review))
Â
7. Sorting Dictionary Entries by Values
Â
Let’s get into dictionaries now! Assume we have a dictionary containing the sales number for each of our products.
sales_data =
'Keychain': 1200,
'T-shirt': 800,
'Mug': 500,
'Magnet': 1500
Â
This single line of code does the job of sorting products in descending sales order:
sorted_sales = dict(sorted(sales_data.items(), key=lambda item: item[1], reverse=True))
Â
8. Filter Entries with filter
Â
You can also filter entries in a Python dictionary by using together the filter and lambda functions as shown below to filter best-selling products (those where 1000 units or more were sold):
best_selling_products = list(filter(lambda item: item[1] > 1000, sales_data.items()))
Â
9. Use reduce
to Perform Aggregations
Â
Performing aggregations over elements in a list cannot be simpler thanks to the reduce function, which in combination with lambda functions helps “reduce” the elements in a collection (such as sales per product) into a single representative value, for instance the total number of sales across all products:
total_sales = reduce(lambda x, y: x + y, sales_data.values())
Â
10. Generate List Permutations
Â
We wrap up with an interesting operator that defines a set of lists given by all possible permutations of a list passed as an argument.
from itertools import permutations
list(permutations(['Alicia', 'Bob', 'Cristina', 'David']))
Â
Need to sit a committee of four in a linear table for an event, and are unsure of which/how many ways to set them one next to another? The permutations will give you all possible solutions.
Â
Â
Iván Palomares Carrascosa is a leader, writer, speaker, and adviser in AI, machine learning, deep learning & LLMs. He trains and guides others in harnessing AI in the real world.