python Modifying slice of list in function

前端 未结 3 647
一向
一向 2021-01-19 02:43

Consider the following piece of code:

def func1(a):
    a[:] = [x**2 for x in a]

a = range(10)
print a  #prints [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
func1(a[:5])
         


        
3条回答
  •  后悔当初
    2021-01-19 03:32

    a[:5] creates a new list. Hence, the changes that func1 applies to it are not mirrorred in a. You could add the slicing to the function:

    def func1(a, start=None, stop=None, step=None):
        start = start if start is not None else 0
        stop = stop if stop is not None else len(a)
        step = step if step is not None else 1
        a[start:stop:step] = [x**2 for x in a[start:stop:step]]
    
    func1(a, stop=5)
    

提交回复
热议问题