0

When the function with a default value a = [], i.e empty list, is called without passing a value to a, the list should be empty.

def func1(x, a = []):
    if x == 5:
        print(a)
        return
    x += 1
    a.append(x)
    func1(x)

func1(1)

At x == 5, it should return [5]. Another case:

def func1(a = []):
    a.append(2)
    return a

print(func1())
print(func1())
print(func1())

Output:

[2]
[2, 2]
[2, 2, 2]

The output should be same each time func1 is called.

Ritik
  • 13
  • 4

1 Answers1

0

That isn't how default arguments work in python.

You should think about default arguments in this way...

def func1(a=[]):
   a.append(2)
   return a

... is almost the same as ...

a=[]
def func1(a):
   a.append(2)
   return a

Except that the a variable isn't accessible to other functions as a global variable would be.

From the python docs:

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

Alexander
  • 16,091
  • 5
  • 13
  • 29
  • This is one of the most common (and famous) duplicates in the entire Python tag. Please try to look for duplicates before answering questions. – Karl Knechtel Aug 23 '22 at 09:55