简体   繁体   中英

What python built-in function can apply some function to every element of list in-place?

I have function sqr(n) and list array . Is there python built-in function that apply sqr(n) to every element of array in-place (elements change inside the array )? Some tricks with map() function or other built-in functions are also wanted.

Of course, this can be done using map() function, but it creates an iterator, and you get a new list (the old list doesn't change):

def sqr(n):
    return n ** 2

array = [1, 2, 3, 4, 5]
array = list(map(sqr, array)) # have to reassign name to new list but elements don't change in old one.
print(array) # output: [1, 4, 9, 16, 25]

I want something like this:

def sqr(n):
    return n ** 2

array = [1, 2, 3, 4, 5]
some_built_in_function(sqr, array)
print(array) # output: [1, 4, 9, 16, 25]

There's no built-in function, but you can accomplish the same result using map and slice assignment.

array[:] = map(sqr, array)

(If you needed an expression rather than a statement, you could use the monstrosity

array.__setitem__(slice(None), map(sqr, array))

which is essentially how the slice assignment is implemented. )

There's no built-in function, but it's easy to write one yourself:

def mapinplace(l, fun):
    for i, val in enumerate(l):
        l[i] = fun(val)

array = [1, 2, 3, 4, 5]
mapinplace(array, sqr)

Since you are most likely operating on numbers, I'll post the obligatory numpy solution. Numpy isn't exactly built-in, but it's pretty close: the @ operator in python was made for numpy, for example.

This solution will only be in-place if the input is a numpy array rather than a list:

np.square(x, out=x)

Most element-wise numpy operations can be done in-place like this.

You can use list comprehension as follows to achieve this

array = [1, 2, 3, 4, 5]
array = [i**2 for i in array]
print(array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM