0

Here I have written a function which takes two lists as argument. But when I called this function passing one list as argument, it works well! Why is this working? Here name_function has two arguments but I passed only one list as argument.

def name_function(names=list(),_list=list()):
    for name in names:
        _list.append(name)
    return _list
print(name_function(['mike','smith','bob']))
roktim
  • 81
  • 2
  • 8
  • If you pass only a single list, then the second list is automatically set to an empty list per: `_list=list()`. – JonSG Jun 15 '21 at 16:32
  • 3
    Because you have default arguments. – dibery Jun 15 '21 at 16:33
  • `names=list()` means that you are creating empty list and passing it to name parameter as default value. Same thing done with _list. – Rima Jun 15 '21 at 16:40
  • Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – L3viathan Jun 15 '21 at 16:52
  • @L3viathan I think OP is asking why default arguments work in the first place. But with mutable defaults, I'm sure that question will be relevant soon enough. ;) – Axe319 Jun 15 '21 at 17:48
  • @dibery yes I have now got this. When two lists are arguments, after passing one list , the later would be default one. – roktim Jun 15 '21 at 18:42

1 Answers1

0
  • Here in the function definition you have initialized both the arguments with the empty list i.e. you are using two default arguments in the function definition.
  • For the above reason the function call works if you provide provide both the arguments or any one of the arguments or no argument at all.
  • To learn more about default arguments in python you can refer this link or this link.
Prabir
  • 1,415
  • 4
  • 10