0

Here is some code that I wrote using Python, got error form extend_list(3) == [3]

I know that because the empty list already in the function so that incoming parameters list extend_list(2,[]) can get [2] extend_list(3) get [1,3]

def extend_list(val, l=[]):
    l.append(val)
    return l

def test_extend_list():
    # 1
    assert extend_list(1) == [1]
    # 2
    assert extend_list(2, []) == [2]
    # 3
    assert extend_list(3) == [3]

if __name__ == '__main__':
    test_extend_list()

================================================== after modified as following :

def extend_list(val, l=[]):
    # l = []
    l.append(val)
    return [l[-1]]

def test_extend_list():
    # 1
    assert extend_list(1) == [1]
    # 2
    assert extend_list(2, []) == [2]
    # 3
    assert extend_list(3) == [3]

if __name__ == '__main__':
    test_extend_list()

My problem is,

if that approach is good for python characteristic? of have another way to have more efficient?

Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22
CYH
  • 1
  • 2
  • 1
    And you are using mutatable default parameter. That's the reason you got `[1,3]`. – Ch3steR Mar 03 '20 at 05:52
  • Yes, you rigft, I mean that problem I can fix, but have another way to solve this problem in more efficient than my method? – CYH Mar 03 '20 at 11:20

0 Answers0