0

I am new to python. I run a code like this:

def funtest(L=[]):
    L.append(L)
    return L
print(funtest([2]))
print(funtest([3]))
print(funtest([4]))

real output is in below.

[2, [...]]
[3, [...]]
[4, [...]]

It is not a new problem about the Mutable Default Arguments. see before: Least Astonishment” and the Mutable Default Argument

According to the Mutable Default Arguments rule, I thought the output should like this:

[2, [...]]
[2,3, [...]]
[2,3,4, [...]]

Does anyone have idea about that? Thanks

Jiang Liang
  • 326
  • 1
  • 2
  • 9
  • Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – finnmglas May 24 '20 at 01:46
  • because that question so I am asking this one – Jiang Liang May 24 '20 at 03:50

1 Answers1

2

default arguments come in picture when you don't pass any arguments to the function,

here you are passing arguments to the function namely [2], [3] and [4] and hence default value is not being used

in your question you mention that for first print output should be [2, [...]] if you are able to understand that , then next ones are exactly same as default argument never comes in the picture.. just focus on how [2, [...]] came

ashish singh
  • 6,526
  • 2
  • 15
  • 35
  • I cannot understand the meaning of default value is not being used. The document say "Python’s default arguments are evaluated once when the function is defined." so I got a infinite [...]. Then I made L=[2], so I got [2, [...]]. It is right according to the saying "if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well." so I make L=[3], it should be [2,3, [...]]. right? – Jiang Liang May 24 '20 at 04:05
  • 1
    @JiangLiang yes, you are creating a default argument when you define the function. Then you never use it, because you always call the function with an explicit argument. – Mark Ransom May 24 '20 at 04:14