alice_v3.0.4 alice_v3.0.4 - 1 month ago 19
Python Question

How to pass slice into a function by reference

If I have

a = [1, 2, 3]

def foo (arr):
for i in len (arr): arr [i] += 1

def bar (arr):
foo (arr[:2])

bar (a)
print (a)


I want output as

>>> [2, 3, 3 ]


How do I go about this?

Motivation: I want a priority queue where I can freeze last N elements, i.e. pass only queue[:N] to heapq.heappush() . But, every time I pass a slice, to it, or to any function in general, it sends a copy of slice and not the actual list to the function, and so my list remains unchanged in the end.

Answer

To be honest instead of going for slice, I would just pass the indexes;

a = [1, 2, 3]
def foo(array, start, stop, jmp= 1):
    for idx in range(start, stop + 1, jmp):
        array[idx] += 1

def bar(array):
    foo(array, 1, 2)
bar(a)
print(a)
[1, 3, 4]
Comments