Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Make Python List Mutable as Its Slice is being changed [duplicate]

Python's slice operation creates a copy of a specified portion a list. How do I pass a slice of a parent list so that when this slice changes, the corresponding portion of the parent list changes with it?

def modify(input):
    input[0] = 4
    input[1] = 5
    input[2] = 6


list = [1,2,3,1,2,3]
modify(list[3:6])
print("Woud like to have: [1,2,3,4,5,6]")
print("But I got: "  + str(list))

Output:

Would like to have: [1,2,3,4,5,6]
But I got: [1,2,3,1,2,3]

like image 662
Shang Jian Ding Avatar asked Sep 17 '26 23:09

Shang Jian Ding


1 Answers

You could do it with numpy if using numpy is an option:

import  numpy as np


def modify(input):
    input[0] = 4
    input[1] = 5
    input[2] = 6


arr = np.array([1,2,3,1,2,3])
modify(arr[3:6])
print("Would like to have: [1,2,3,4,5,6]")
print("But I got: "  + str(arr))

Would like to have: [1,2,3,4,5,6]
But I got: [1 2 3 4 5 6]

Using basic indexing always returns a view which is An array that does not own its data, but refers to another array’s data instead

Depending on your use case and if you are using python3 maybe a memeoryview with an array.array might work .

from array import array

arr = memoryview(array("l", [1, 2, 3, 1, 2, 3]))

print(arr.tolist())

modify(arr[3:6])

print("Woud like to have: [1,2,3,4,5,6]")
print((arr.tolist()))
[1, 2, 3, 1, 2, 3]
Woud like to have: [1,2,3,4,5,6]
[1, 2, 3, 4, 5, 6]
like image 154
Padraic Cunningham Avatar answered Sep 19 '26 13:09

Padraic Cunningham