Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

answered 4 years ago

Juanjo gravatar image

It is not really a SageMath problem, but a Python one. I do not know why xL is not the empty list each time that test() is called, according to the default value of xL in your definition of test. However, this happens even if such a default value is not an empty list, as you can check with any Python interpreter:

>>> def test(xL=[0]):
...     xL.append(len(xL))
...     return xL
... 
>>> for i in range(3):
...     print(test())
... 
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]

However, it one uses concatenation instead of the append method, one gets the expected behaviour:

>>> def test(xL=[0]):
...     return xL + [len(xL)]
... 
>>> for i in range(3):
...     print(test())
... 
[0, 1]
[0, 1]
[0, 1]
click to hide/show revision 2
No.2 Revision

It is not really a SageMath problem, but a Python one. I do not know why xL is not the empty list each time that test() is called, according to the default value of xL in your definition of test. However, this happens even if such a default value is not an empty list, as you can check with any Python interpreter:

>>> def test(xL=[0]):
...     xL.append(len(xL))
...     return xL
... 
>>> for i in range(3):
...     print(test())
... 
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]

However, it if one uses concatenation instead of the append method, one gets the expected behaviour:

>>> def test(xL=[0]):
...     return xL + [len(xL)]
... 
>>> for i in range(3):
...     print(test())
... 
[0, 1]
[0, 1]
[0, 1]