Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition on list slice

Why does the code

l = [0, 1, 2, 3, 4, 5, 6, 7]
l[2:5] += [10]
print(l)

Give the output

[0, 1, 2, 3, 4, 10, 5, 6, 7]

It is inserting the 10 in between, but I want to add 10 to indexes 2 to 4.

I also tried

l = [0, 1, 2, 3, 4, 5, 6, 7]
l[2:5] += 10
print(l)

But it is showing an error saying int not iterable. Shouldn't it automatically covert to [10, 10, 10, 10] and add to the required slice?

like image 698
Pawan Avatar asked Mar 25 '26 15:03

Pawan


1 Answers

Lists can be added like this:

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]

Notice that the left list is extended by the right, not that the elements are added together.

The operator += (as in a += b) is equivalent to a = type(a).__iadd__(a, b). __iadd__ is the in-place equivalent of __add__, which is regular +.

In your case, the expression l[2:5] += [10] becomes

l[2:5] = list.__iadd__(l[2:5], [10])

On the right hand side, the slice l[2:5] extracts a temporary object, which is modified in-place by extending it with the contents of 10. On the left hand side, you replace elements 2:5 with the new, longer, list.

It should be pretty clear at this point why the scalar assignment fails entirely.

Remember that lists can hold anything, not just numbers, and must have reasonable behavior in those cases too. If you want to add something to the subset of a list, you have to go through each element individually:

for i in range(2, 5):
    l[i] *= 10

Numpy is probably a better way to do this if you are working with purely numerical data. Numpy arrays support exactly the sort of addition operator you are looking for:

>>> import numpy as np
>>> a = np.array(l)
>>> a[2:5] += 10
>>> a
array([  0,  1, 12, 13, 14,  5,  6,  7])
like image 82
Mad Physicist Avatar answered Mar 27 '26 03:03

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!