Alonzo Castanon
Alonzo Castanon

Reputation: 11

Can you use a list or other iterable as input for a function that takes an arbitrary number of arguments?

I created a function that takes an arbitrary number of variables via the *args feature. Now another function needs to call this original function using a list of varying length, but I can't seem to find a solution. As a simplified example:

def print_all(*args):
    for x in args:
        print(x)

print_all([1,2,3,4,5])

Running this, the console displays:

[1,2,3,4,5]

But I would like it to display:

1
2
3
4
5

Is there a way to turn an iterable like this into proper input for a function that accepts *args like above?

Upvotes: 0

Views: 89

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174766

Remove the * which exists in the parameter part of the function definition. Here * is unnecessary.

def print_all(args):
    for x in args:
        print(x)

Upvotes: 0

JuniorCompressor
JuniorCompressor

Reputation: 20025

The following will do the trick:

print_all(*[1,2,3,4,5])

With the star operator every item in the list is like been passed as a separate argument to the function.

Upvotes: 3

Related Questions