0

I recently started playing around with Python 3 (or coding, for that matter) and I quickly ran into something that I don't understand. I somehow managed to define a function that not only gives the wrong output, but also unexpectedly changes its input. I'll explain this more precisely on an example.

Say we want to write a function that takes a list/vector

L = [v_0, ..., v_n]

and spits out the following transformed version:

L' = [v_0, v_0+v_1, ..., v_0+...+v_n]

Even if there are better ways, let's try to do it using this algorithm:

  • Step 0: Set L_0=L as initial data.
  • Step 1: Take L_0=L and add v_0 to L_0[j] for j>1. Call the result L_1.
  • ...
  • Step i: Take L_i and add v_i to L_i[j] for j>i. Call the result L_i.
  • ...

This gives L' in n steps (hopefully...). As I said, there are probably better ways to do it, but let's stick with this approach. Here's what I tried to do:

# problematic function:
def Mod(L):
    newL = L
    for i in range(len(L)-1):
        for j in range(i+1,len(V)):
            newL[j] = newL[j] + L[i]
    return newL

# illustration of problem:
L = [1,2,3,4]
print(L)        # gives [1,2,3,4], as expected
print(Mod(L))   # gives [1,3,7,15], L' would be [1,3,4,10]
print(L)        # gives [1,3,7,15] instead of [1,2,3,4]. WHY?!

Again, I'm not looking for better solutions or better algorithms. This is an artificial problem and I've already solved my actual problem in another way. What I want is to understand why this code does not work properly and why it does what it does.

As indicated, there are two things that are going wrong:
(1) First of all, 'Mod' does not do what I want: Mod(L) does not give L'.
(2) More importantly, for some reason running Mod(L) changes the variable L.

I'm seriously stumped by this, especially by (2). I keep going through the loops trying to find out what's wrong, but I seem to be stuck in a loop myself (overlooking the same thing again and again). Somehow the input of Mod must get redefined somewhere in the loops. But I don't see where this would be happening. The only thing that I see getting changed is the local variable 'newL'.

Any pointers as to what I'm missing are highly appreaciated!

Stefan B.
  • 101
  • 3

0 Answers0