Thread Rating:
• 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!

Watch the video if you want to learn more details about this technique:

## 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/

Forum Jump:

 Users browsing this thread: 1 Guest(s)

 Active Threads (Indie Deal) The GameCreators 2 Bundle, ... Last Post: xSicKxBot Today 08:59 AM » Replies: 0 » Views: 41 (Free Game Key) Free DLC for Steam game ... Last Post: xSicKxBot Today 08:59 AM » Replies: 0 » Views: 4 Microsoft - 4 approaches to comprehensiv... Last Post: xSicKxBot Today 08:59 AM » Replies: 0 » Views: 4 News - Review: Pinchcliffe Grand Prix – ... Last Post: xSicKxBot Today 08:58 AM » Replies: 0 » Views: 6 News - GTA Online Adds New Double Down M... Last Post: xSicKxBot Today 08:58 AM » Replies: 0 » Views: 9 [Tut] Python __set_name__() Magic Method Last Post: xSicKxBot Yesterday 07:31 PM » Replies: 0 » Views: 69 Godot 3.5 Beta Released Last Post: xSicKxBot Yesterday 07:30 PM » Replies: 0 » Views: 7 AppleInsider - Dutch App Store change al... Last Post: xSicKxBot Yesterday 07:30 PM » Replies: 0 » Views: 7 Microsoft - EzPC: Increased data securit... Last Post: xSicKxBot Yesterday 07:30 PM » Replies: 0 » Views: 7 News - Community Focus: GamerGirlGrey Last Post: xSicKxBot Yesterday 07:30 PM » Replies: 0 » Views: 7

 Twitter Tweets by _SickGaming

 Sponsored