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
I was wondering if there are any other solutions to this, similar to a list comprehension or something like that. I'm new to Python so this is purely for exploration purposes.
You could use a slice assignment for this:
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).Example: