0

So I have to following code with the goal to add some offset to measurement data.

This works as planned:

IndexMax = [3, 10, 20, 30]
IndexMax2 = [3, 10, 20, 30] #Just for Computing purposes


for x in range(0, len(IndexMax)):
  if x == 0:
      IndexMax2[0] = 0; #First Data has no Offset per Definition
  elif len(IndexMax2) >= 1: #The 
      IndexMax2[x] = IndexMax[x-1] + IndexMax2[x-1]
      tmp = IndexMax2


print('Offsets are ' + str(tmp))

The Correct Output is given:

Offsets are [0, 3, 13, 33]

But what does not work is the same as a funtion with Indexmax as an argument:

def Offsetcalcalculater(IndexMax):
     IndexMax = IndexMax
     IndexMax2 = IndexMax


     for x in range(0, len(IndexMax)):
         if x == 0:
              IndexMax2[0] = 0; #First Data has no Offset per Definition
         elif len(IndexMax2) >= 1: #The 
              IndexMax2[x] = IndexMax[x-1] + IndexMax2[x-1]
              tmp = IndexMax2
     return IndexMax2

Calling it with

IndexMaxtest = [3, 10, 20, 30]
IndexMax2 = Offsetcalcalculater(IndexMaxtest)

leads to:

IndexMax2 [0, 0, 0, 0]

Why does the function not behave in the same way as the code above?

2 Answers 2

1

You are doing a shallow copy of IndexMax Both IndexMax and IndexMax2 referring same list

IndexMax    Indexmax2
#    |            |
#    |            |
#     \          /  
#      \        /
#       IndexMax  

To solve this use .copy to make a copy of the list.

def Offsetcalcalculater(IndexMax):
     IndexMax = IndexMax
     IndexMax2 = IndexMax.copy() #---->


     for x in range(0, len(IndexMax)):
         if x == 0:
              IndexMax2[0] = 0; #First Data has no Offset per Definition
         elif len(IndexMax2) >= 1: #The 
              IndexMax2[x] = IndexMax[x-1] + IndexMax2[x-1]
              tmp = IndexMax2
     return IndexMax2
Sign up to request clarification or add additional context in comments.

Comments

0
IndexMax = [3, 10, 20, 30]
IndexMax2 = [3, 10, 20, 30]

are two references to two different lists. If you change one, the second one won't change.

 IndexMax = IndexMax
 IndexMax2 = IndexMax

on the other hand, are two references to the same list. Changing something in IndexMax will lead to the same change in IndexMax2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.