0

I am trying to implement bestSum algorithm in python and I have the following script with the issue at line 13,14.

memo = {}
def bestSum(s, l):
    if s == 0:
        return []
    elif s < 0:
        return None
    elif s in memo:
        return memo[s]
    minList = None
    for i in l:
        temp = bestSum(s-i, l)
        if temp != None:
            temp = temp + [i] #This works LINE13
            # temp.append(i) This does not work LINE14
            if minList == None or len(temp) < len(minList):
                minList = temp

    memo[s] = minList
    return minList

I know that "+" operator return a new list while the append function mutates the original list.

My question is why does it matter in my code as the temp list is only being used in the next few lines. Why are they giving different outputs.

  • Does this answer your question? [Python append() vs. + operator on lists, why do these give different results?](https://stackoverflow.com/questions/2022031/python-append-vs-operator-on-lists-why-do-these-give-different-results) – not_speshal Jun 04 '21 at 16:49
  • 1
    Mutating the list means you are modifying the contents of `memo`, rather than preparing a *distinct* list to be added to `memo`. – chepner Jun 04 '21 at 16:50
  • Thanks chepner, your answer helped. Never though it would alter the value in memo. – Shubhankar Singh Jun 04 '21 at 17:22
  • @ShubhankarSingh *of course it does*. If you add a list to a dict, then you mutate the list, well, the list will be mutated and the dictionary will reflect that. Adding objects to containers never copies those objects, at least not in Python built-ins. – juanpa.arrivillaga Jun 04 '21 at 17:25

3 Answers3

1

The problem is not about a difference between append(i) and + [i], it's about how objects work in python. You got close to nailing it down.

First off, minilist = temp makes minilist refer to the same list object temp refers to, so appending to temp also appends to minilist. Meanwhile temp = temp + [i] makes temp a new reference to a new object, while minilist keeps the reference to the original list.

You can see that this is the reason by, for example, in the LINE13 version converting it to += [i], this makes temp keep it's reference thus it would alter both lists. In the LINE14 version you can add temp = temp.copy() before the append to make it a new object.

Mike Jack
  • 130
  • 9
0

The + operator is used when you add a list by concatenating the element. The append method, append the item on the right side that you give it, instead of taking its elements, if you want to have a result similar to the + operator try to use extend()

Jan
  • 42,290
  • 8
  • 54
  • 79
0

The difference is that the "+" operation acts specifically when you add an array by concatenating the element. The "append" method appends the object on the right-hand side that you give it, instead of taking the elements.