Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass list elements as arguments

Tags:

python

I want to pass elements of list as function arguments like this:

def foo(a, b, c):
    # do something

list = [1, 2, 3]
foo(list)

I can't use foo(list[0], list[1], list[2]), because I don't know how many elements the list has and how many arguments the function takes.

like image 721
KsaneK Avatar asked Dec 06 '14 13:12

KsaneK


People also ask

Can a list be passed as an argument?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

How do you pass list elements as parameters in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.


1 Answers

Use the * argument unpacking operator:

seq = [1, 2, 3]
foo(*seq)

So in the input function you could use

getattr(self, func)(*args)

PS. Don't name your variables list, since it shadows the built-in of the same name.

like image 150
unutbu Avatar answered Oct 13 '22 22:10

unutbu