0

I want to group students into two different lists according to the subjects but the function is failing to create different lists. I am aware that the instance of the list created in both cases is the same but I am unable to find a workable solution to the same.

def add_tolist(name, students=[]):
       students.append(name)
       return students
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print idc101, idc306

The results should be : ['shyam', 'deepa'] ['ram']

But its printing : ['ram', 'shyam', 'deepa'] ['ram', 'shyam', 'deepa']

  • Mutable default: https://dev.to/florimondmanca/python-mutable-defaults-are-the-source-of-all-evil-6kk – rdas Apr 19 '19 at 19:14

1 Answers1

0

I think the problem was that your program treated the new list as not a distinct new copy, this will fix that.

def add_tolist(name, students=[]):
    students1 = students.copy()
    students1.append(name)
    return students1
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print (idc101, idc306)

output: ['shyam', 'deepa'] ['ram']

akerr
  • 11
  • 1
  • 5