Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying list slice passed into a function

Is it possible to pass a slice of a list into a function and modify the list via the slice?

This doesn't seem to work:

def foo(a_list):
  a_list[0]='abc'

x=[1,2,3,4]
foo(x[0:2])

I want x to now be x=['abc',2,3,4]

like image 724
LoveToCode Avatar asked Dec 11 '22 22:12

LoveToCode


1 Answers

No. A "list slice" in the sense you describe is nothing but a new list. When you do x[0:2], the resulting list does not "know" that it was created as a slice of another list. It's just a new list.

What you could do is pass in the slice object itself, separately from the list:

def foo(a_list, a_slice):
  a_list[a_slice]='abc'

>>> foo(x, slice(0, 2))
>>> x
['a', 'b', 'c', 3, 4]
like image 160
BrenBarn Avatar answered Jan 05 '23 08:01

BrenBarn