0

I have a list of zeroes and one, and I am finding each position where zero occurs. Here is my code.

sample = [1, 0, 1, 0, 1]
ind = []
for i in range(0, 5):
  ind.append(sample.index(0))
  sample[sample.index(0)] = 1

print(ind)

This code is showing ValeError: 0 is not in the list

  • 2
    Does this answer your question? [How to find all occurrences of an element in a list](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – AcaNg Aug 27 '21 at 07:47
  • 1
    In your own words, when you write `for i in range(0, 5):`, what do you expect that to mean? How many times do you expect the loop to run? How many times *should* the loop run? – Karl Knechtel Aug 27 '21 at 08:06

1 Answers1

3

Just try enumerate:

print([i for i, v in enumerate(sample) if v == 0])

Output:

[1, 3]

To fix up your code, try:

sample = [1, 0, 1, 0, 1]
ind = []
for i in range(0, 5):
    if 0 in sample:
        ind.append(sample.index(0))
        sample[sample.index(0)] = 1

print(ind)

The reason your code didn't work is because after a while the 0s disappear from the list, so sample.index(0) would give an error. You need to add a condition if 0 is still in the list sample.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114