← Back to Nested Lists

Count a Value

4 of 6

Exercise 3: Count a Value

Count how many times a specific value appears in a 2D grid.

grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ]

Expected output:

Number of X's: 4

Starter Code

grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ] count = ___ for row in grid: for cell in row: if ___: count += ___ print(f"Number of X's: {count}")

Hints

Hint 1 — Initialize the counter

Start with count = 0 before the loops.

Hint 2 — What to check?

Check if each cell equals "X": if cell == "X":

Hint 3 — Increment

Add 1 each time you find an "X": count += 1


Bonus Challenge

Make it work for any value! Ask the user what to search for:

target = input("What to search for? ") # Count how many times target appears

Solution

Show Solution
grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ] count = 0 for row in grid: for cell in row: if cell == "X": count += 1 print(f"Number of X's: {count}")
Show Bonus Solution
grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ] target = input("What to search for? ") count = 0 for row in grid: for cell in row: if cell == target: count += 1 print(f"Number of '{target}': {count}")

Try it yourself

Code: Count a Value

Loading Python runtime…
Python
Loading...
bash
$ Click "Run" to execute your code...