• 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.

Get your Python One-Liners Now!!

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

 Possibly Related Threads… Thread Author Replies Views Last Post [Tut] Overriding in Python xSicKxBot 0 0 13 minutes ago Last Post: xSicKxBot [Tut] How to Install PIL/Pillow in Python? A Helpful Illustrated Guide xSicKxBot 0 5 10-27-2020, 12:00 AM Last Post: xSicKxBot [Tut] How to Read a File Line-By-Line and Store Into a List? xSicKxBot 0 6 10-24-2020, 06:12 PM Last Post: xSicKxBot [Tut] How To Kill A Thread In Python? xSicKxBot 0 8 10-24-2020, 05:40 AM Last Post: xSicKxBot [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 18 10-16-2020, 10:30 PM Last Post: xSicKxBot [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 21 10-10-2020, 08:24 PM Last Post: xSicKxBot [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 22 10-09-2020, 06:13 PM Last Post: xSicKxBot [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 41 10-02-2020, 04:24 AM Last Post: xSicKxBot [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 38 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 43 09-29-2020, 09:02 PM Last Post: xSicKxBot

Forum Jump:

Become a Patron!
 Upcoming Events

 Latest Threads [Tut] Overriding in Python Last Post: xSicKxBot Today 04:49 AM » Replies: 0 » Views: 0 (Indie Deal) ?FREE Dyna Bomb, Big Quiz E... Last Post: xSicKxBot Today 04:49 AM » Replies: 0 » Views: 0 ODIN 2 Synthesizer VST Last Post: xSicKxBot Yesterday 11:24 PM » Replies: 0 » Views: 2 Microsoft - Cyberattacks target internat... Last Post: xSicKxBot Yesterday 11:24 PM » Replies: 0 » Views: 1 Fedora - What’s new in Fedora 33 Worksta... Last Post: xSicKxBot Yesterday 11:24 PM » Replies: 0 » Views: 1 News - No More Heroes 1 & 2 Are Both Ava... Last Post: xSicKxBot Yesterday 11:24 PM » Replies: 0 » Views: 1 News - Bravely Default 2 Preorders Are L... Last Post: xSicKxBot Yesterday 11:24 PM » Replies: 0 » Views: 2 (Indie Deal) Tropico 6, Assassin's Creed... Last Post: xSicKxBot Yesterday 04:41 PM » Replies: 0 » Views: 4 gRPC performance improvements in .NET 5 Last Post: xSicKxBot Yesterday 04:40 PM » Replies: 0 » Views: 2 News - Season of the Hunt Last Post: xSicKxBot Yesterday 04:40 PM » Replies: 0 » Views: 2

 Twitter Tweets by _SickGaming