IndigoChild
IndigoChild

Reputation: 844

Combining functions in python

I need to run a function as following:

def func1(a):
    l=a+1
    print (l)

def func2(a,b):
    l=a+1
    z.append(l)
    l=b+1
    z.append(l)
    print (l)

def func2(a,b,c):
    l=a+1
    z.append(l)
    l=b+1
    z.append(l)
    l=c+1
    z.append(l)
    print (l)

and so on. Can somebody show me an alternative where I can combine all these functions to one function where I can add as many values as I want (a,b,c,d..) and the output given will be a+1,b+1,c+1,d+1... in a list?

Upvotes: 0

Views: 380

Answers (3)

zipa
zipa

Reputation: 27869

I think you want variable number of arguments with list output:

def myFunc(*args):
    return [i+1 for i in args]

Now you can get your z from this function like this:

z = myFunc(1,2,3,4)
z
#[2, 3, 4, 5]

Upvotes: 1

Stephen Rauch
Stephen Rauch

Reputation: 49784

You can define a function to take a variable number of parameters, and then use a list comprehension to work on them in one statement like:

Code:

def increment_to_list(*args):
    return [a + 1 for a in args]

Test Code:

print(increment_to_list(1,2,3))
print(increment_to_list(4,5,6,7,8))

Results:

[2, 3, 4]
[5, 6, 7, 8, 9]

Upvotes: 4

Keith Dowd
Keith Dowd

Reputation: 661

I think you want to do something like this:

def f(*args):
    l = []
    for i in args:
        l.append(i+1)

    return l

Or, if you like list comprehensions like me, you could do:

def f(*args):
    return [val + 1 for val in args]

Upvotes: 2

Related Questions