'Change array dimensions of function parameter in python

I am using python3 and numpy. I have following code on many places in my

if contour.condition:
     contour = contour[0, :, :]

I want to do it in a function like

 def CorrectContour(contour):
     if contour.condition:
         contour = contour[0, :, :]

But this change only the the copy of contour. How can I do this? I accept other suggestions, except functions.



Solution 1:[1]

contour[0,:,:] makes a new array, a view. contour=... assigns the new array to the variable. What's different in the function is that contour is now a local variable, breaking the connection with the input argument.

This should behave the same as your original code:

def CorrectContour(contour):
     if contour.condition:
         contour = contour[0, :, :]
     return contour
contour = CorrectContour(contour)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hpaulj