1

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
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
RR_28023
  • 158
  • 2
  • 12
  • 1
    Does this answer your question? [How to set first N elements of array to zero?](https://stackoverflow.com/questions/31049544/how-to-set-first-n-elements-of-array-to-zero) – kishore Rajendran Jan 03 '21 at 19:02

2 Answers2

1

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

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

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:

Generator expression

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]
wjandrea
  • 28,235
  • 9
  • 60
  • 81