RR_28023
RR_28023

Reputation: 168

Pythonic way to update a subset of a list with the same value

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

Upvotes: 1

Views: 961

Answers (2)

wjandrea
wjandrea

Reputation: 32987

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]

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

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.

Upvotes: 1

Related Questions