I am doing this:
for f in range(n, n + k + 1):
mylist[f] = 0
Wondering if I could do something like:
mylist[f:f+k] = 0
I am doing this:
for f in range(n, n + k + 1):
mylist[f] = 0
Wondering if I could do something like:
mylist[f:f+k] = 0
Yes, you can perform the similar operation but via using list object on the right. For example:
my_list = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
f, k = 2, 3
my_list[f:f+k] = [0]*k
# ^ List of size "k" i.e. 3
# Updated value of "my_list":
# [1, 1, 0, 0, 0, 1, 1, 1, 1, 1]
In the above example, k
number of elements from the f
th index in my_list
will be replaced with the corresponding values from the list on the right.
Please refer How assignment works with Python list slice? for more details regarding how it works.
Yes, this is called slice assignment. You just need an object on the right-hand side containing k items.
Instead of making a temporary list like in Moinuddin's answer, you could use an iterator. I believe this will be more efficient for large k. Here are two options:
mylist = [100, 101, 102, 103, 104, 105]
f = 2
k = 3
mylist[f:f+k] = ('a' for _ in range(k))
print(mylist) # -> [100, 101, 'a', 'a', 'a', 105]
itertools.repeat()
from itertools import repeat
mylist[f:f+k] = repeat('b', k)
print(mylist) # -> [100, 101, 'b', 'b', 'b', 105]