← 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...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect

βœ… Functions, classes, recursion, print()

❌ No file system, subprocess, OS access, or network requests

❌ No pip install (all supported modules are pre-loaded)

⏱️ 5 second execution time limit