1

im trying to pass the address of an array reg_value[2] to a function in python

import array
reg_value = array.array('I',[0]*100)

def postdata(data):
        for i in range(2):
            print(data[i])

reg_value[0]=1
reg_value[1]=2
reg_value[2]=3
reg_value[3]=4

postdata(reg_value)

the above code prints the value 1 2

but i need to pass the address of reg_value[2] to print the value 3 4

i can achieve this in C programming like passing the address as &reg_value[2]

how to replicate the same in python?

Pravin
  • 13
  • 3
  • 1
    C & Python are quite different for this. The easiest way to print 34 in your case is print ```reg_value[2]``` and ```reg_value[3]``` like you did for the indexes 0 & 1 – Metapod Jul 30 '21 at 13:32
  • Thanks, but this is just an example program. in real i need to send hundreds of values in an array to function for processing data. where the array index will vary in runtime. – Pravin Jul 30 '21 at 13:42
  • 1
    Does this answer your question? [Passing subset reference of array/list as an argument in Python](https://stackoverflow.com/questions/12509557/passing-subset-reference-of-array-list-as-an-argument-in-python) – Gino Mempin Jul 31 '21 at 01:06

2 Answers2

0

You can't pass the address of anything in Python, but you can pass a slice which contains a subsequence.

postdata(reg_value[2:])

This does create a copy of the items from the sequence. Probably a better design is to allow the caller to specify a base index.

def postdata(items, offset=0):
    for i in range(2):
        print(items[offset+i])
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • This is an `array.array` instance, not a list. – user2357112 Jul 30 '21 at 13:39
  • I don't see how that invalidates this answer. Or do you mean there is a better way to do it with this specific data type? – tripleee Jul 30 '21 at 13:42
  • There does happen to be a better way to do it for `array.array` instances (take a memoryview and slice that, to avoid the copy), but I was mostly just pointing out it's an array because you kept saying "list". – user2357112 Jul 30 '21 at 13:51
  • Thanks, but is there any other method to avoid sending offset as an argument to the function? – Pravin Aug 03 '21 at 10:00
  • I'm sure there are other ways, but maybe post a new question with more details about why this is unacceptable and what sort of solution you would like instead. – tripleee Aug 03 '21 at 10:17
-1
for i in range(2,4):
    print(data[i])
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • An explanation of how this solves the problem would greatly improve this answer. Also, this hardcoded `range(2,4)` will not handle OP's case where "*where the array index will vary in runtime.*" – Gino Mempin Jul 31 '21 at 01:04