#๐Ÿ”’ Passing reference to a numpy array into function

110 messages ยท Page 1 of 1 (latest)

fiery turret
#

How to do properly what i am trying to do here

import numpy as np
A = np.zeros((3, 3))
def modify (a):
     a = ([1,1,1],
          [1,1,1],
          [1,1,1])

modify(A)
print(A)
```py
charred solarBOT
#

@fiery turret

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

amber magnet
#

You can't do this literally in Python. You'd need to return the new object, or put A into a mutable container.

#

I'd just return it.

fiery turret
#

OMG

#

NOW I HAVE TO REWRITE ALL MY CODE

#

nice scam by python

#

can i make a dictionary

#

from arrays?

amber magnet
fiery turret
#
D2Q4 = np.zeros((SIZE + 1, SIZE + 1, 4))
D2Q4_new = D2Q4.copy()
D2Q5 = np.zeros((SIZE + 1, SIZE + 1, 5))
D2Q5_new = D2Q4.copy()
D2Q9 = np.zeros((SIZE + 1, SIZE + 1, 9))
D2Q9_new = D2Q4.copy()
#

i have 3 arrays

#

can i make something to iterate though them

harsh thunder
#

!e

import numpy as np 

A = np.zeros((3,3))

def modify(a):
    a[:] = np.ones((3,3))

modify(A)
print(A)```
charred solarBOT
#

@harsh thunder :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | [[1. 1. 1.]
002 |  [1. 1. 1.]
003 |  [1. 1. 1.]]
fiery turret
#

oh shit

#

it works now!

#

well

#

that was ez

amber magnet
#

That's because [:] overwrites the previous contents of the list, which is different than reassigning the reference.

fiery turret
#

i don't understand

rain marsh
#

you can also just do A[:] = 1

#

much easier

harsh thunder
#

didn't know that, neat

fiery turret
#

no i have a complex function

#

so would need to pass to a function

amber magnet
#

Note that the two have different effects. Your original attempt tried to create a new array, which would have left other code with a reference to the old object unaffected. This way mutates the array, which will be reflected by everyone referencing the object.

#

So, just make sure you're careful of who has references if you're going to mutate the array.

fiery turret
#

well

#
def make_one_step():
    main.D2Q4_new = D2Q4.copy()
    for y in range (len(D2Q4)):
        for x in range (len(D2Q4)):
            for m in range(len(D2Q4[0][0])):
                modify_Tm(x,y,m)
    main.D2Q4 = D2Q4_new.copy()
#

thats a function i'm planning to pass my array to

#

since i have 3 arrays now

#

i don't wanna make 3 instances of this function

rain marsh
#

you'll want to pass the array in modify_Tm(main.D2Q4_new, x,y,m)

#
def operate(array, i, j, k):
  array[i, j, k] *= 2
``` or whatever
fiery turret
#

now its also necessary to pass array further to modify_Tm function

#
def modify_Tm(x, y, m):
    if m == 0:
        flag1 = find_nearest_node(x-1)
        flag2 = Tm(flag1, y, m)
        flag3 = Tm_eq(flag1, y)
    elif m == 1:
        flag1 = find_nearest_node(y-1)
        flag2 = Tm(x, flag1, m)
        flag3 = Tm_eq(x, flag1)
    elif m == 2:
        flag1 = find_nearest_node(x+1)
        flag2 = Tm(flag1, y, m)
        flag3 = Tm_eq(flag1, y)
    elif m == 3:
        flag1 = find_nearest_node(y+1)
        flag2 = Tm(x, flag1, m)
        flag3 = Tm_eq(x, flag1)
    elif m == 4:
        flag2 = Tm(x, y, m)
        flag3 = Tm_eq(x, y)
    elif m == 5:
        flagx = find_nearest_node(x - 1)
        flagy = find_nearest_node(y - 1)
        flag2 = Tm(flagx, flagy, m)
        flag3 = Tm_eq(flagx, flagy)
    elif m == 6:
        flagx = find_nearest_node(x + 1)
        flagy = find_nearest_node(y - 1)
        flag2 = Tm(flagx, flagy, m)
        flag3 = Tm_eq(flagx, flagy)
    elif m == 7:
        flagx = find_nearest_node(x + 1)
        flagy = find_nearest_node(y + 1)
        flag2 = Tm(flagx, flagy, m)
        flag3 = Tm_eq(flagx, flagy)
    elif m == 8:
        flagx = find_nearest_node(x - 1)
        flagy = find_nearest_node(y + 1)
        flag2 = Tm(flagx, flagy, m)
        flag3 = Tm_eq(flagx, flagy)
    D2Q4_new[y][x][m] = flag2 - W * (flag2 - flag3)
rain marsh
plush basalt
#

That's the wettest if block ever

rain marsh
#

โŒ

global_mutable_variable = "x"
do_work()
print("result:", global_mutable_variable)

โœ… ```py
result = do_work("x")
print("result:", result)

#

With the former, it is really difficult to understand how your functions work without first understanding the ENTIRE PROGRAM

#

nobody wants to have to understand the entire program just to fix one small issue

#

When your functions modify something outside of the function, that's called a "side effect" and they're really annoying

#

somtimes unavoidable, but in this case it certainly is

fiery turret
#

its the only function modfiying that array

#

literally

rain marsh
#

mhm so call modify_Tm(array, x, y, m)

#

dont use a nonlocal variable

#

also, this isn't a use-based subscription service, you don't have to use single letter variable names and abbreviations

#

like wtf is flagx, flagy, flag2, flag3, D2Q4, D2Q4_new, Tm, modify_Tm, Tm_eq, x, y, m, W

#

none of your variables make any sense, this is complete gibberish

fiery turret
#

x and y

#

are literally axes

rain marsh
#

(don't start explaining what they mean, please just use real names instead)

fiery turret
#

how else would i call axes

#

lol

#

its

#

x

#

and

#

y

fiery turret
#

anyway

#

since my array is 3 dimensional

#

how would i use 2 dots to modify elements

rain marsh
# fiery turret how else would i call axes

i have a feeling this is a rhetorical question but I'll answer it anyway
Based on the context, I have a feeling that your rows and columns have more inherit meaning than simply being a coordinate system (based on the name D2Q4). If that's not true, then names like x and y could be appropriate, but since these at least represent indices/locations, you could better express their meaning by doing x_index or simply ix (but most people won't do that). Alternatively, names like row and col make it really clear what the variables purposes are

rain marsh
#

there are many ways to slice numpy arrays using colons

fiery turret
#

so in my make one step function i'm modifying element by element through a loop

rain marsh
#

yep that's what you're doing

#

if main.D2Q4isn't being modified then that's because D2Q4_new in your modify_Tm refers to a different array than the main.D2Q4_new in your make_one_step

rain marsh
fiery turret
#
D2Q4_new[y][x][m][:] = flag2 - W * (flag2 - flag3)
#

like that?

rain marsh
#

no your code already properly modifies an array

fiery turret
#

i know

#

but i am about to add 2 more array

#

and iterate through them

rain marsh
#

!e ```py
import numpy as np

D2Q4_new = np.zeros((2, 2, 2))
D2Q4_new[1][1][1] = 123

print(D2Q4_new)

charred solarBOT
#

@rain marsh :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | [[[  0.   0.]
002 |   [  0.   0.]]
003 | 
004 |  [[  0.   0.]
005 |   [  0. 123.]]]
fiery turret
#

caz i'm not making 2 more instances of function

rain marsh
rain marsh
#

imagine you want to modify both "x", "y", and "z"

with the โŒ code, you have to do:

x = [1,2,3]
do_work_on_x()

y = [4,5,6]
do_work_on_y()

z = [7,8,9]
do_work_on_z()

print("results:", x, y, z)
``` where you have to create three separate functions

now consider the equivalent โœ… code:
```py
x = do_work([1,2,3])
y = do_work([4,5,6])
z = do_work([7,8,9])

print("results:", x, y, z)
fiery turret
#

u want me to assign?

#

i was about to start assigneing before you gave me 2 dots thing

rain marsh
#

your question has nothing to do with the colon, :

#

your question is about how to make a function work with multiple different inputs

fiery turret
#

: is so good it modifies arrays

rain marsh
#

you pass in the variable as an argument

#

!e ```py
def modify(arr, index):
arr[index] = 123
return arr

print(modify([1,2,3], 0))
print(modify([4,5,6], 1))
print(modify([7,8,9], 2))

charred solarBOT
#

@rain marsh :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | [123, 2, 3]
002 | [4, 123, 6]
003 | [7, 8, 123]
rain marsh
#

look at this, I used a single function to modify three different arrays

rain marsh
fiery turret
#

i literally need globals

#

i need to make many steps and save data about them

fiery turret
#

wait

#
D2Q4 = np.zeros((SIZE + 1, SIZE + 1, 4))
D2Q4_new = D2Q4.copy()
D2Q5 = np.zeros((SIZE + 1, SIZE + 1, 5))
D2Q5_new = D2Q4.copy()
D2Q9 = np.zeros((SIZE + 1, SIZE + 1, 9))
D2Q9_new = D2Q4.copy()
#

need to iterate though this

#

and also each of 3 arrays needs to be assosiated with its copy

#

would dictionary work

plush basalt
fallow smelt
charred solarBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.