Python Default Parameter Gotcha

  • September 8, 2019
  • Python

Take a look at this code. All it does is return a list with appended parameter. In case no list is supplied, it defaults to an empty list and appends to it. Or is it??? def add_to_list(item, item_list=[]): item_list.append(item) return item_list add_to_list(“gold”) # expected: [“gold”] #actual: [“gold”] add_to_list(“silver”) # expected: [“silver”] #actual: [“gold”,”silver”] Look at […]