Mar-26-2018, 08:17 PM
Because the data structure is a list, which is mutable. When you assign something to a variable (
Using your example...
x = 42
), the old value of the variable still exists, but there's a new binding to the new value. But with lists, the actual variable was never reassigned, the only thing that changed was the contents of the list.Using your example...
>>> def f(x): ... x[0] = x[0] * 2 ... return "unrelated string" ... >>> x = [5, 4, 3, 2, 1, 0] >>> f(x) 'unrelated string' >>> x [10, 4, 3, 2, 1, 0] >>> # but if we were to re-assign x, instead of using an element... ... >>> def f(x): ... x = ['green', 'eggs', 'and', 'spam'] ... return 0 ... >>> x [10, 4, 3, 2, 1, 0] >>> f(x) 0 >>> x [10, 4, 3, 2, 1, 0]