Basically, I have to use a function to modify a list in a way where I change n-consecutive elements. The problem is, however, that I cannot return the list (the function can't return anything really), so to my understanding, I cannot create a new list, because that will not change the list that I got through my function argument.
I've done it with a while loop like this:
while i < length:
my_list[index+i] = element
i += 1
You could use a slice assignment for this:
my_list[index:index + length] = (e for _ in range(length)) # or (e,) * length
The line above will replace the elements of
my_list at positions within the
[index, index + length) interval with elements from the iterable at the right hand side of the assignment. Note that the length of the slice and the length of the iterable must match. Otherwise, some of the elements will be removed (if the iterable is shorter) or more elements will be added (in case the iterable is longer).
In : my_list = [1, 2, 3, 4, 5, 6] In : index, length, element = 1, 3, 0 In : my_list[index:index + length] = (element for _ in range(length)) In : my_list Out: [1, 0, 0, 0, 5, 6]