George Waat George Waat - 1 month ago 6
Python Question

How to change n consecutive elements in a list without creating a new one?

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.

Answer

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).

Example:

In [14]: my_list = [1, 2, 3, 4, 5, 6]

In [15]: index, length, element = 1, 3, 0

In [16]: my_list[index:index + length] = (element for _ in range(length))

In [17]: my_list
Out[17]: [1, 0, 0, 0, 5, 6]