w3resource

Recursive Python function: Count None values in list


7. Recursive None Counter

Write a Python function that counts None values in a list recursively. Return 0 if the list is empty.

Sample Solution:

Code:

def count_none(input_list):
    if not input_list:
        return 0
    
    head, *tail = input_list
    if head is None:
        return 1 + count_none(tail)
    else:
        return count_none(tail)

def main():
    try:
        values_list = [None, "Red", None, 8, None, True]
        result = count_none(values_list)
        
        print("Number of None values:", result)
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":
    main()

Output:

Number of None values: 3

In the exercise above, the "count_none()" function uses recursion to process the input list. It checks if the list is empty; if it is, it returns 0. Alternatively, it separates the first element (head) from the rest (tail). In case head is 'None', it increments the count and calls the function recursively with the remaining tail. If head is not 'None', it calls the function recursively with the remaining tail. The "main()" function demonstrates the function's usage by providing a sample list of values.

Flowchart:

Flowchart: Check even or odd number using Boolean variables in Python.

For more Practice: Solve these Related Problems:

  • Write a Python function that recursively counts the number of None values in a list and returns 0 if the list is empty.
  • Write a Python program to implement a recursive algorithm that iterates through a list and sums the occurrences of None, returning the count.
  • Write a Python function to traverse a list recursively, counting None elements, and then test it on nested lists.
  • Write a Python script to recursively count and print the number of None values in a large list, returning 0 for an empty list.

Python Code Editor :

Previous: Python dictionary value retrieval with key check.
Next: Sum with None check

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.