Skip to content
Advertisement

While iterating over a list, how can I fill the remainder with a number once a condition has been met?

I have an array = [0, 0, 0, 0, 0, 0, 0, 0].

And say I want to fill in the remainder of my array with 1s, once a certain condition has been met.

For example,

for i in range(len(array)):
    i%2 == 0:
        array[i:] = 1

The above produces a:

TypeError: can only assign an iterable.

How can I change my code to achieve the above?

(P.S.: Is it possible to do it with list comprehension?)

Expected output:

array = [1, 1, 1, 1, 1, 1, 1, 1]

Advertisement

Answer

You can take a slice of the part before the insertion point and concatenate a list with that constant value repeated (NB: you need if, and you probably want to break out the loop):

if <condition>:
    array = array[:i] + [1]*(len(array)-i)
    break
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement