1

given:

def psum(a,b,c):
    return a**b+c

and x = [1,2] and y = 3 how can I do psum(*x,3) --> an equivalent.

I do not want to do x[0], x[1] because a function returns x and calling it twice would be inefficient. Could one do z = function(a). where z = x. and then do z[0], z[1].

But I'm wondering if one can do this otherwise and use positional arguments in such a way.

Also, without using a wrapper.

Edit: One cannot use names because I didn't implement the function and the function writers did not use named arguments :/

1
  • Also, note that if you have x -- x = func(...), then you can index x naturally. It won't call the function again. x = func(); psum(x[0],x[1],3) only calls func once. Commented Oct 12, 2012 at 18:25

2 Answers 2

2

You can do this:

psum(*x + [y])
Sign up to request clarification or add additional context in comments.

1 Comment

it works! and he winss :). you can do any order of *x + [2], [2] + x... etc it seems. now what about interspersed keyword and positional e.g. func(a=2,b,c,d=7) ;)
1

In this case, the order of your arguments doesn't matter, so psum(3,*x) will work.

In the slightly-more-general case, if you know the names of the arguments,

psum(*x,c=3)

seems to work for me as well, but it won't work if sum is defined so that it takes varargs ...

I don't think there is a way to do this in the completely general case without modifying the object you pass to psum:

x.append(3)
psum(*x)

9 Comments

sorry. fixed. order matters. i'm thinking ideally plot(x,y,z) is my problem and i'm using meshgrid(x,y) to get x,y
I think you can do something like x_out,y_out = meshgrid(x,y) so that the result is two separate objects.
The problem is that named arguments cannot follow a * pointer type expression. So either name all of the arguments, or write the function to handle an iterable, or use *args and **kwargs in the definition. I don't think this is very satisfactory on Python's part, but it is what it is.
@Eiyrioü von Kauyf, check out meshgrid's docs: link. The main use case is such that you get two separate objects back, rather than a tuple of them.
@EMS: wrong. 1. Named arguments may follow *expression: f(*[1,2],c=3) is legal 2.A function always returns a single object in Python (it may be a tuple).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.