Search code examples
pythonlistin-placesub-array

Python, how can I change in-place a sub array?


For example, I have a function

def foo(a):
    a[0],a[1] = a[1], a[0]

And

a = [1,2,3]

The foo(a) changes value of a in-place but foo(a[:1]) does not. Please help to let me know how can I make foo(a[:1]) change value of a in-place


Solution

  • As others have mentioned, when you slice a list it creates a new copy, which is what you are modifying in-place instead. Consider either:

    def foo(a):
        a[0], a[1] = a[1], a[0]
        return a
    
    a = [1,2,3]
    a[1:] = foo(a[1:])
    

    or

    def foo(a, i=0):
        a[i], a[i+1] = a[i+1], a[i]
    

    where i is your slice index.