PandasSeries
PandasSeries

Reputation: 49

Python how to reduce this two-liner to one line?

x = f1(x)
x = f2(x, x)

How do I write this in a single line? Obviously I don't want to write x = f2(f1(x), f1(x)) since it performs the same operation twice, but do I really have to do a two-liner here?

Upvotes: 0

Views: 148

Answers (3)

Grady Shoemaker
Grady Shoemaker

Reputation: 31

This really doesn't seem like a good place to condense things down to one line, but if you must, here's the way I would go about it.

Let's take the function f2. Normally, you'd pass in parameters like this:

x = f2("foo", "bar")

But you can also use a tuple containing "foo" and "bar" and extract the values as arguments for your function using this syntax:

t = ("foo", "bar")
x = f2(*t)

So if you construct a tuple with two of the same element, you can use that syntax to pass the same value to both arguments:

t = (f1(x),) * 2
x = f2(*t)

Now just eliminate the temporary variable t to make it a one-liner:

x = f2(*(f1(x),) * 2)

Obviously this isn't very intuitive or readable though, so I'd recommend against it.

One other option you have if you're using Python 3.8 or higher is to use the "walrus operator", which assigns a value and acts as an expression that evaluates to that value. For example, the below expression is equal to 5, but also sets x to 2 in the process of its evaluation:

(x := 2) + 3

Here's your solution for a one-liner using the walrus operator:

x = f2(x := f1(x), x)

Basically, x is set to f1(x), then reused for the second parameter of f2. This one might be a little more readable but it still isn't perfect.

Upvotes: 0

Pig
Pig

Reputation: 567

This is horrendous, and 2 clear lines is better than 1 obfuscated line, but...

x = f2(*itertools.repeat(f1(x), 2))

Example of use:

import itertools
def f1(x):
    return 2*x
def f2(x1, x2):
    return x1+x2
x = 1
x = f2(*itertools.repeat(f1(x), 2))
print(x)

Prints 4.

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95908

You should probably just keep it as two lines, it is perfectly clear that way. But if you must you can use an assignment expression:

>>> def f1(a): return a + 42
...
>>> def f2(b, c): return b + c
...
>>> f2(x:=f1(1), x)
86
>>>

But again, don't try to cram your code into one line. Rarely is a code improved by trying to make a "one-liner". Write clear, readable, and maintainable code. Don't try to write the shortest code possible. That is maybe fun if you are playing code-golf, but it isn't what you should do if you are trying to write software that is actually going to be used.

Upvotes: 1

Related Questions