Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python converting *args to list

This is what I'm looking for:

def __init__(self, *args):
  list_of_args = #magic
  Parent.__init__(self, list_of_args)

I need to pass *args to a single array, so that:

MyClass.__init__(a, b, c) == Parent.__init__([a, b, c])
like image 494
Daniel Watson Avatar asked Mar 18 '13 23:03

Daniel Watson


People also ask

Is * args a list in Python?

The *args is a special argument preceded by a star ( * ). When passing the positional arguments 10 , 20 , 30 , and 40 to the function, Python assigns 10 to x , 20 to y , and a tuple (30, 40) to args . It's like tuple unpacking except that the args is a tuple, not a list.

How do you convert an argument to a string in Python?

Python has a built-in function str() which converts the passed argument into a string format. The str() function returns a string version of an object. The object can be int , char , or a string . If the object is not passed as an argument, then it returns an empty string.

Can you pass a list to * args?

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

Can I pass a list to args in Python?

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.


2 Answers

Nothing too magic:

def __init__(self, *args):
  Parent.__init__(self, list(args))

Inside of __init__, the variable args is just a tuple with any arguments that were passed in. In fact you can probably just use Parent.__init__(self, args) unless you really need it to be a list.

As a side note, using super() is preferable to Parent.__init__().

like image 87
Andrew Clark Avatar answered Sep 19 '22 13:09

Andrew Clark


There is this piece of code that I picked up in sentdex tutorials that deals with this:

https://www.youtube.com/watch?v=zPp80YM2v7k&index=11&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ

Try this:

def test_args(*args):
    lists = [item for item in args]
    print lists

test_args('Sun','Rain','Storm','Wind')

Result:

['Sun', 'Rain', 'Storm', 'Wind']

like image 31
Simon Avatar answered Sep 18 '22 13:09

Simon