Count the number of null elements in a list in Python

In this Python tutorial, we will learn, “How to count the number of null elements in a list in Python”.

  • Lists in Python are similar to arrays in C or Java. A list represents a group of elements.
  • The main difference between a list and an array is that a list can store different types of elements but an array can store only one type.
  • Instead of numbers, characters, strings, etc., a list can also contain “null elements” as shown in the below example,
list2 = ["hi","ram","","shyam",""]
  • In the above code, if we try to print the element at index 2 & 4 i.e. list2[2] & list2[4] then we will get only a blank screen in the output which indicates that the elements at indexes 2 & 4 are null elements.
  • Using the “for” loop:  The first approach is traversing the list using loop and check whether the current element is a null element or not. If the current element is the null element then increase the counter by 1.
li = [10,"venu gopal","",'M',""] # Consider any random list
cnt = 0                          #Initialize a counter variable

for i in range(len(li)):         # for loop used to traverse the list 
                                 # from 0 up to the length of the list

  if(li[i]==""):     #if element at "li[i]" is a null element 
                     #then increase the counter value by 1
    cnt+=1

print("Number of null elements in list li is: "cnt)                       # Finally print the value of counter
Number of null elements in list li is: 2
  • Using  “count” function: There is an inbuilt function in Python “count( )” that returns the number of occurrences of an element inside a Python list.  Syntax:name_of_list.count(object), where “object” is the element whose count from the list is to be returned. Consider the following snippet,
list2 = ["list2","","","Hello","","World"]   # Predefined list

print(list2.count(""))     #Here we are simply printing the value 
                           #returned by the "count" that takes ""(null element) as the parameter.

Output: 3

Also read:

Leave a Reply