In Python, in-place addition of elements can be performed in an element-wise manner using the +=
operator. Here is an example:
a = [1, 2, 3]
b = [4, 5, 6]
# add elements of b to a in-place
for i in range(len(a)):
a[i] += b[i]
print(a) # Output: [5, 7, 9]
In this example, we have two lists a
and b
, and we want to perform in-place addition of their elements in an element-wise manner. To do this, we use a for
loop to iterate over the elements of a
and b
simultaneously and add them using the +=
operator. This will change the values of a
in-place without creating a new list.
Asked: 2021-05-01 11:00:00 +0000
Seen: 7 times
Last updated: Aug 07 '22