Find indices with None values in given list in Python


Manytime when dealing with data analysis we may come across the None values present in a list. These values can not be used directly in mathematical operations and string operations etc. So we need to find their position and either convert them or use them effectively.

With range()

Combining the range and len function we can compare the value of each element with None and capture their index positions. Of course we use a for loop design to achieve this.

Example

 Live Demo

listA = ['Sun', 'Mon',None, 'Wed', None, None]

# Given list
print("Given list : ",listA)

# Using range
positions = [i for i in range(len(listA)) if listA[i] == None]

# Result
print("None value positions : ",positions)

Output

Running the above code gives us the following result −

Given list : ['Sun', 'Mon', None, 'Wed', None, None]
None value positions : [2, 4, 5]

With enumerate

We can also use the enumerate function which lists out ech element. Then we compare each element with the None value and select its position as shown below in the program.

Example

 Live Demo

listA = ['Sun', 'Mon',None, 'Wed', None, None]

# Given list
print("Given list : ",listA)

# Using enumarate
positions = [i for i, val in enumerate(listA) if val == None]

# Result
print("None value positions : ",positions)

Output

Running the above code gives us the following result −

Given list : ['Sun', 'Mon', None, 'Wed', None, None]
None value positions : [2, 4, 5]

Updated on: 26-Aug-2020

497 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements