How to count the number of zeros in Python?

count, list, python-2.7

Solution

Have you printed `rows`?

It's `[[0, 1, 0, 0, 2], [1, 2, 0, 1, 2], [3, 1, 1, 1, 1], [1, 0, 0, 1, 0], [0, 3, 2, 0, 1]]`, so you have a nested list there.

If you want to count the number of `0`'s in those nested lists, you could try:

import random

convert = {0:0, 1:1, 2:2, 3:3, 4:0, 5:1, 6:2, 7:1}
rows = [[convert[random.randint(0, 7)] for _ in range(5)] for _ in range(5)]

numgood = 25 - sum(e.count(0) for e in rows)
print numgood

Output:

18

Problem

My code is currently written as: ``` convert = {0:0,1:1,2:2,3:3,4:0,5:1,6:2,7:1} rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)] numgood = 25 - rows.count(0) print numgood >> 25 ``` It always comes out as 25, so it's not just that rows contains no 0's.

Original source