Replace every second and third item in list with 0

Issue

I have a randomly generated list of items, and I want to replace every second and third item in that list with the number 0. For the replacement of every second item I have used the code below.

import random

x = [random.randint(0,11) for x in range(1000)]
y = [random.randint(0,11) for x in range(1000)]
a = (x + y)
a[::2] = [0]*(2000//2)
print(a)

It works fine, but I can’t use the same method with replacing every third item since it gives me an error

attempt to assign sequence of size 666 to extended slice of size 667

I thought of using list comprehension, but I’m unsure of how to execute it, and I could not find a definite answer in my research.

Solution

You can simply replace 2000//2 with len(a[::2]) like this

import random

x = [random.randint(0,11) for x in range(1000)]
y = [random.randint(0,11) for x in range(1000)]

a = (x + y)
a[::2] = [0]*len(a[::2])
print(a)

b = (x + y)
b[::3] = [0]*len(b[::3])
print(b)

Answered By – Marius ROBERT

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published