• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
[Tut] Python One Line Function Definition

Python One Line Function Definition

A lambda function allows you to define a function in a single line. It starts with the keyword `lambda`, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, `lambda x, y: x+y` calculates the sum of the two argument values `x+y` in one line of Python code.

Problem: How to define a function in a single line of Python code?

Example: Say, you’ve got the following function in three lines. How to compress them into a single line of Python code?

```def say_hi(*friends): for friend in friends: print('hi', friend) friends = ['Alice', 'Bob', 'Ann']
say_hi(*friends)
```

The code defines a function `say_hi` that takes an iterable as input—the names of your friends—and prints `'hi x'` for each element `x` in your iterable.

The output is:

```'''
hi Alice
hi Bob
hi Ann '''```

Let’s dive into the different methods to accomplish this! First, here’s a quick interactive overview to test the waters:

Exercise: Run the code—is the output the same for all four methods?

Next, you’ll learn about each method in greater detail!

## Method 1: Lambda Function

You can use a simple lambda function to accomplish this.

A lambda function is an anonymous function in Python. It starts with the keyword `lambda`, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, `lambda x, y, z: x+y+z` would calculate the sum of the three argument values `x+y+z`.

```friends = ['Alice', 'Bob', 'Ann'] # Method 1: Lambda Function
hi = lambda lst: [print('hi', x) for x in lst]```

In the example, you want to print a string for each element in an iterable—but the lambda function only returns an object. Thus, we return a dummy object: a list of `None` objects. The only purpose of creating this list is to execute the print() function repeatedly, for each element in the `friends` list.

You obtain the following output:

```hi(friends) '''
hi Alice
hi Bob
hi Ann '''```

## Method 2: Function Definition

A similar idea is employed in this one-liner example—but instead of using a lambda function, we define a regular function and simply skip the newline. This is possible if the function body has only one expression:

```friends = ['Alice', 'Bob', 'Ann'] # Method 2: Function Definition
def hi(lst): [print('hi', x) for x in lst]```

The output is the same as before:

```hi(friends) '''
hi Alice
hi Bob
hi Ann '''```

This approach is more Pythonic than the first one because there’s no throw-away return value and it’s more concise.

## Method 3: exec()

The third method uses the `exec()` function. This is the brute-force approach to one-linerize any multi-liner!

To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character `'\n'` and pass the result into the `exec(...)` function. You can run this script from the outside (command line, shell, terminal) by using the command `python -c "exec(...)"`.

We can apply this technique to the first example code snippet (the multi-line function definition) and rename the variables to make it more concise:

```friends = ['Alice', 'Bob', 'Ann'] # Method 3: exec()
exec("def hi(*lst):\n for x in lst:\n print('hi', x)\nhi(*friends)")```

If you run the code, you’ll see the same output as before:

```hi(friends) '''
hi Alice
hi Bob
hi Ann '''```

This is very hard to read—our brain cannot grasp the whitespaces and newline characters easily. But I still wanted to include this method here because it shows how you or anyone else can compress complicated algorithms in a single line of Python code!

## Python One-Liners Book

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:

Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

https://www.sickgaming.net/blog/2020/09/...efinition/

 Possibly Related Threads… Thread Author Replies Views Last Post [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 7 10-16-2020, 10:30 PM Last Post: xSicKxBot [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 15 10-10-2020, 08:24 PM Last Post: xSicKxBot [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 16 10-09-2020, 06:13 PM Last Post: xSicKxBot [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 27 10-02-2020, 04:24 AM Last Post: xSicKxBot [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 29 10-01-2020, 02:21 AM Last Post: xSicKxBot [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 30 09-29-2020, 09:02 PM Last Post: xSicKxBot [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 32 09-28-2020, 02:36 AM Last Post: xSicKxBot [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 29 09-25-2020, 07:51 PM Last Post: xSicKxBot [Tut] Python One Line Dictionary xSicKxBot 0 35 09-21-2020, 05:58 PM Last Post: xSicKxBot [Tut] Python Import Error (ModuleNotFoundError) xSicKxBot 0 31 09-20-2020, 04:15 PM Last Post: xSicKxBot

Forum Jump:

Become a Patron!
 Upcoming Events

 Latest Threads Roblox Going Public Last Post: xSicKxBot Yesterday 08:41 PM » Replies: 0 » Views: 3 Fedora - Web of Trust, Part 2: Tutorial Last Post: xSicKxBot Yesterday 08:41 PM » Replies: 0 » Views: 2 News - DC’s Static Shock Movie On The Wa... Last Post: xSicKxBot Yesterday 08:41 PM » Replies: 0 » Views: 2 (Indie Deal) PlugInDigital & Kalypso Str... Last Post: xSicKxBot Yesterday 01:57 PM » Replies: 0 » Views: 9 News - Kingdom Hearts Director Possibly ... Last Post: xSicKxBot Yesterday 01:57 PM » Replies: 0 » Views: 5 News - Double Fine Brings Classic LucasA... Last Post: xSicKxBot Yesterday 01:57 PM » Replies: 0 » Views: 6 News - Video: Why your game community is... Last Post: xSicKxBot Yesterday 01:12 PM » Replies: 0 » Views: 6 News - Sharpen your storytelling skills ... Last Post: xSicKxBot Yesterday 01:12 PM » Replies: 0 » Views: 6 News - Poll: Box Art Brawl #64 – Interna... Last Post: xSicKxBot Yesterday 07:56 AM » Replies: 0 » Views: 3 News - Grant Kirkhope’s Goal Is To Compo... Last Post: xSicKxBot Yesterday 07:56 AM » Replies: 0 » Views: 2