If I were trying to input a list as an argument to a function in Python, is there any way to retain the argument as a list or will it have to be passed in one element at a time?
-
2Please follow How to create a Minimal, Complete, and Verifiable example.AKS– AKS2016-04-22 06:28:50 +00:00Commented Apr 22, 2016 at 6:28
-
Could you add some examples ?Shekhar Samanta– Shekhar Samanta2016-04-22 06:36:57 +00:00Commented Apr 22, 2016 at 6:36
-
2By default the argument will still be a list and not a series of variablesMetareven– Metareven2016-04-22 06:39:03 +00:00Commented Apr 22, 2016 at 6:39
4 Answers
If you pass the list as is, then it will stay as a list.
>>> def myfunc(*args):
for arg in args:
print(arg)
>>> sample_list = [1, 2, 3]
>>> myfunc(sample_list)
[1, 2, 3]
The function prints the list as one item.
However, if you use the 'splat' or 'unpack' operator *, the list can be passed as multiple arguments.
>>> myfunc(*sample_list)
1
2
3
Comments
The syntax you are looking for is this:
my_list = ["arg1", "arg2", None, 4, "arg5"]
print(*my_list)
is equivalent to:
print("arg1", "arg2", None, 4, "arg5")
4 Comments
print(args[0], args[1], args[2]) and not what really happens. Anyways, let OP decide.You get the object inside the function that you pass as argument. If your argument is a list, then you get a list inside the function, of course as one proper list and not as single variables.
def func1(my_list):
print(type(my_list), my_list)
func1([1, 2, "abc"])
# output: <type 'list'> [1, 2, "abc"]
However, you can use several ways to achieve something else. You can...
Pass single arguments when calling the function, but receive all of them as single tuple (immutable list).
def func2(*my_list): # the * means that this parameter collects # all remaining positional arguments print(type(my_list), my_list) func2(1, 2, "abc") # output: <type 'tuple'> (1, 2, "abc")Unpack a list in the function call and receive the elements as single arguments.
def func2(arg1, arg2, arg3): print(type(arg1), arg1, type(arg2), arg2, type(arg3), arg3) func2(*[1, 2, "abc"]) # the * unpacks the list to single positional arguments # output: <type 'int'> 1 <type 'int'> 2 <type 'str'> abc