[Tutor] How default arg of function works
Deepak Dixit
deepakdixit0001 at gmail.com
Thu Jun 14 03:04:57 EDT 2018
I am learning python and working with function.
Here is my test program :-
program.py
------------------------------------
def test1(nums=[]):
return nums
def test2(nums=[]):
nums.append(len(nums));
return nums
print "Calling test1"
print '=' * 40
print 'test1()', test1()
print 'test1([1,2])', test1([1,2])
print 'test1()', test1()
print 'test1([1,1,1])', test1([1,1,1])
print 'test1()', test1()
print "Calling test2"
print '=' * 40
print 'test2()', test2()
print 'test2([1,2,3])', test2([1,2,3])
print 'test2([1,2])', test2([1,2])
print 'test2()', test2()
print 'test2()', test2()
--------------------------------------------------
# python program.py
Calling test1
========================================
test1() [ ]
test1([1,2]) [1, 2]
test1() [ ]
test1([1,1,1]) [1, 1, 1]
test1() [ ]
Calling test2
========================================
test2() [0]
test2([1,2,3]) [1, 2, 3, 3]
test2([1,2]) [1, 2, 2]
test2() [0, 1]
test2() [0, 1, 2]
I am assuming that in test1() we are not doing any modification in the
passed list and because of that its working as per my expectation.
But when I am calling test2() with params and without params then both are
using different references. Why ? Can you please help me to understand
this.
--
With Regards,
Deepak Kumar Dixit
More information about the Tutor
mailing list