Home > Mobile >  function with input parameters that will convert them into a list inside its body
function with input parameters that will convert them into a list inside its body

Time:12-08

Is there a way to create a function like the one below and then to have those parameters being added to a list inside the function's body?

def create_list(x, y, z, w, t):

CodePudding user response:

Here you must make use of *args in your function that would be defined something like this

def make_list(*args):
    return list(args)

print(make_list(1,2,3, "Spiderman", ("Gilfoyle", "Dinesh", "Richard"), {"wizardName": "Harry Potter", "age": 21}))

Output for the above code

[1, 2, 3, 'Spiderman', ('Gilfoyle', 'Dinesh', 'Richard'), {'wizardName': 'Harry Potter', 'age': 21}]

Here you can pass any number of arguments of any type and they will be converted into a list and returned back to you. We need to write return list(args) because it returns a tuple by default. Since you require a list, we need the list() function to be called.

Reference

  1. *args and **kwargs in python
  • Related