Home > database >  assigning an item in a list using a function to get the desired address
assigning an item in a list using a function to get the desired address

Time:11-14

how can I return the address of the value in the list I wish to change?

I can change a value in a list in this manner:

a = [1, 2, 3]
a[0] = 0

but how can I change a value that a helper function choose?

helper = lambda x: x[0]
a = [1, 2, 3]
helper(a) = 0

will produce a runtime error type syntax error (because python interpret it like 1 = 0)

my question is how can I build a function that chooses the index for me?

functions that return only the index are not helpful:

example:

helper = lambda x: 0
a = [1, 2, 3]
a[helper(a)] = 0

will not solve the problem for (for example) 2d lists:

helper_1 = lambda x: 0, 0
a = [[1, 2, 3]]
a[helper(a)[0]][helper(a)[1]] = 0

as you can see this makes the code very ugly very fast.

I will provide two simple examples for this issue:

first example code, 1d list:

lst = [1, 2, 3]
for x in lst:
    x *= 2
# will not change the list

if there were pointers:

for &x in lst:
    *x *= 2

second example code, 2d list:

def rotate_90(image, direction):
    rows, columns = len(image), len(image[0])
    rotated = empty_2d(columns, rows) # allocate 2d list
    
    rotated_place = lambda row, col: rotated[col][-1- row] \
                     if direction =='R' else \
                    lambda row, col: rotated[-1-col][row]
        
    for row in range(rows):
        for col in range(columns):
            rotated_place(row, col) = image[row][col] # error
            
    return rotated
# will produce an error

if there were pointers:

def rotate_90(image, direction):
    rows, columns = len(image), len(image[0])
    rotated = empty_2d(columns, rows) # aloccate memory
    
    rotated_place = lambda row, col: &rotated[col][-1- row] \
                     if direction =='R' else \
                    lambda row, col: &rotated[-1-col][row]
        
    for row in range(rows):
        for col in range(columns):
            *rotated_place(row, col) = image[row][col]
            
    return rotated

CodePudding user response:

Changing a bit for clarity, you want this to print [42, 2, 3]:

first = ...

a = [1, 2, 3]
first(a) = 42

print(a)

You can make it work with first[a] instead of first(a):

class First:
    def __setitem__(_, lst, value):
        lst[0] = value
first = First()

a = [1, 2, 3]
first[a] = 42

print(a)

Try it online!

  • Related