14
votes

I need to set a subset of a list to a specific value based on a tuple with bounds (start,end).

Currently I'm doing this:

indexes = range(bounds[0], bounds[1] + 1)
for i in indexes:
   my_list[i] = 'foo'

This doesn't seem good to me. Is there a more pythonic approach?

3
You can use slice assignment, but I think your method is fine. By the way, the plural of index is indices. - wim
Honestly, they way you're doing it is fine and readable, I don't think that compressing it down to one line adds anything. - Andrew Barrett
@wim, I too prefer indices, but most modern dictionaries recognize both as acceptable. - senderle
@wim I think 'indexes' might be more common in US/Canada, whereas 'indices' is more common in the UK/Oz - armandino
Just to re-emphasise a point, I would consider the way you are doing it in your question more pythonic than the answers using slice assignment. The zen of python states, "simple is better than complex". You're just setting several elements of a list to a value, there is no need for slice assignment there, all that is doing is introducing more scope for bugs by making you calculate more values (through the generation of the array that you are assigning through). Keep what you have. - Andrew Barrett

3 Answers

18
votes

Use slice assignment:

my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])

or using local variables to add your + 1 only once:

lower, upper = bounds
upper += 1
my_list[lower:upper] = ['foo'] * (upper - lower)

You may want to store the upper bound as non-inclusive, to play better with python and avoid all the + 1 counts.

Demo:

>>> my_list = range(10)
>>> bounds = (2, 5)
>>> my_list[bounds[0]:bounds[1] + 1] = ['foo'] * ((bounds[1] + 1) - bounds[0])
>>> my_list
[0, 1, 'foo', 'foo', 'foo', 'foo', 6, 7, 8, 9]
5
votes
>>> L = list("qwerty")
>>> L
['q', 'w', 'e', 'r', 't', 'y']
>>> L[2:4] = ["foo"] * (4-2)
>>> L
['q', 'w', 'foo', 'foo', 't', 'y']
1
votes

Here is a more efficient version of the solution by @MartijnPieters using itertools.repeat

import itertools
lower, upper = bounds
upper += 1
my_list[lower:upper] = itertools.repeat('foo', (upper - lower))