Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
call by objects problem
#1
def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l) 

f(2)
f(3,[3,2,1])
f(3)
Output:
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
I can understand the first two implementation of f(), but not the third. Can someone help explain why the third output starting with 0,1, which is the memory left by the first f() result?
Reply
#2
read this
http://docs.python-guide.org/en/latest/writing/gotchas/

you should NOT use mutable default arguments
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list call problem in generator function using iteration and recursive calls postta 1 1,920 Oct-24-2020, 09:33 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020