Skip to content Skip to sidebar Skip to footer

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 retu

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

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]

Post a Comment for "How To Change N Consecutive Elements In A List Without Creating A New One?"