When using the slice operator it refers to sub-part of the list, so operating on it requires a list too (we can use the "add" operator on list
with list
, and not with an int
, unlike in some other languages).
Therefore the following:
array[1:3] += 2
Throws:
TypeError: 'int' object is not iterable
Because 2
is not a list (actually an iterable, which is more general than list
).
But:
array[1:3] += [100, 100]
Works and adds (actually appends) the two elements in the middle (index 3
) of array
according to indexes:
[3, 2, 3, 100, 100, 4, 0]
Without using a for
loop, as requested
If you want to add to the values in the slice:
array = [1,2,3,4,0]
array.__setitem__(slice(1, 3), [x+2 for x in array[1:3]])
# [1, 102, 103, 4, 0]
print(array)
Which can be written also as:
array = [1,2,3,4,0]
def apply_on_slice(lst, start, end, callable):
array.__setitem__(slice(start, end), [callable(x) for x in array[start:end]])
apply_on_slice(array, 1, 3, lambda x : x + 100)
# [1, 102, 103, 4, 0]
print(array)
Using a for loop
Here are some other options to do so, elegantly:
array[1:3] = (x+2 for x in array[1:3])
Or of course, using a regular for loop, which is more efficient than using slicing twice:
for i in range(1, 3):
array[i] += 2