2

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]

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Shang Jian Ding
  • 1,931
  • 11
  • 24
  • You can't do that using regular Python lists. You could instead pass the list and indices separately (e.g., `modify(list, 3, 6)`) and have `modify` use them to modify the list. – BrenBarn May 15 '15 at 16:52
  • 2
    @thefourtheye: That doesn't make sense, since his goal is mutate the object. – BrenBarn May 15 '15 at 16:52
  • Just use a slice assignment: `li=[1,2,3,1,2,3]` then `li[3:6]=[4,5,6]` – dawg May 15 '15 at 17:17

1 Answers1

6

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]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321