Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python one line function definition

Tags:

python

This must be simple, but as an only occasional python user, fighting some syntax. This works:

def perms (xs):     for x in itertools.permutations(xs): yield list(x)  

But this won't parse:

def perms (xs): for x in itertools.permutations(xs): yield list(x)  

Is there some restriction on the one-line function syntax? The body definition (for...) can be either two or one line by itself, and the def: can be one or two lines with a simple body, but combining the two fails. Is there a syntax rule that excludes this?

like image 742
guthrie Avatar asked May 26 '13 04:05

guthrie


People also ask

How do you define a one line 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: x+y calculates the sum of the two argument values x+y in one line of Python code.

What is single line function?

Single Row functions - Single row functions are the one who work on single row and return one output per row. For example, length and case conversion functions are single row functions.

What is single line in Python?

What is a single line comment in python? Single line comments are those comments which are written without giving a line break or newline in python. A python comment is written by initializing the text of comment with a # and terminates when the end of line is encountered.

How do you write a one line function?

Here's the most Pythonic way to write a function in a single line of code: f2 = lambda x: str(x * 3) + '! ' You create a lambda function and assign the new function object to the variable f2 .


2 Answers

If you must have one line just make it a lambda:

perms = lambda xs: (list(x) for x in itertools.permutations(xs)) 

Quite often, when you have a short for loop for generating data you can replace it with either list comprehension or a generator expression for approximately the same legibility in slightly less space.

like image 132
Sean Vieira Avatar answered Sep 21 '22 15:09

Sean Vieira


Yes, there are restrictions. No, you can't do that. Simply put, you can skip one line feed but not two.

See here.

The reason for this is that it would allow you to do

if test1: if test2: print x else:     print y 

Which is ambiguous.

like image 36
Lennart Regebro Avatar answered Sep 19 '22 15:09

Lennart Regebro