How to extract parameters from a list and pass them to a function call

PythonListArgument Unpacking

Python Problem Overview


What is a good, brief way to extract items from a list and pass them as parameters to a function call, such as in the example below?

Example:

def add(a,b,c,d,e):
    print(a,b,c,d,e)

x=(1,2,3,4,5)

add(magic_function(x))

Python Solutions


Solution 1 - Python

You can unpack a tuple or a list into positional arguments using a star.

def add(a, b, c):
    print(a, b, c)

x = (1, 2, 3)
add(*x)

Similarly, you can use double star to unpack a dict into keyword arguments.

x = { 'a': 3, 'b': 1, 'c': 2 }
add(**x) 

Solution 2 - Python

I think you mean the * unpacking operator:

>>> l = [1,2,3,4,5]
>>> def add(a,b,c,d,e):
...    print(a,b,c,d,e)
...
>>> add(*l)
1 2 3 4 5

Solution 3 - Python

Use the * operator. So add(*x) would do what you want.

See this other SO question for more information.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfalek.marcinView Question on Stackoverflow
Solution 1 - PythonCat Plus PlusView Answer on Stackoverflow
Solution 2 - PythonTim PietzckerView Answer on Stackoverflow
Solution 3 - PythonarunkumarView Answer on Stackoverflow