Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find indices with None values in given list in Python
Many times when dealing with data analysis we may come across None values present in a list. These values cannot be used directly in mathematical operations and string operations. So we need to find their position and either convert them or use them effectively.
Using range() with List Comprehension
Combining the range() and len() functions we can compare the value of each element with None and capture their index positions using list comprehension ?
Example
days = ['Sun', 'Mon', None, 'Wed', None, None]
# Given list
print("Given list :", days)
# Using range
positions = [i for i in range(len(days)) if days[i] == None]
# Result
print("None value positions :", positions)
The output of the above code is −
Given list : ['Sun', 'Mon', None, 'Wed', None, None] None value positions : [2, 4, 5]
Using enumerate()
We can also use the enumerate() function which provides both index and value for each element. Then we compare each element with the None value and select its position ?
Example
days = ['Sun', 'Mon', None, 'Wed', None, None]
# Given list
print("Given list :", days)
# Using enumerate
positions = [i for i, val in enumerate(days) if val == None]
# Result
print("None value positions :", positions)
The output of the above code is −
Given list : ['Sun', 'Mon', None, 'Wed', None, None] None value positions : [2, 4, 5]
Using NumPy (For Large Arrays)
When working with large datasets, NumPy provides a more efficient approach using numpy.where() ?
Example
import numpy as np
# Convert to numpy array (None becomes np.nan for object arrays)
arr = np.array(['Sun', 'Mon', None, 'Wed', None, None], dtype=object)
# Find None positions
positions = np.where(arr == None)[0]
print("Array :", arr)
print("None value positions :", positions.tolist())
The output of the above code is −
Array : ['Sun' 'Mon' None 'Wed' None None] None value positions : [2, 4, 5]
Comparison
| Method | Best For | Performance |
|---|---|---|
range() |
Small lists, explicit indexing | Moderate |
enumerate() |
Most readable, Pythonic | Good |
NumPy where()
|
Large datasets, scientific computing | Best for large data |
Conclusion
Use enumerate() for most cases as it's readable and Pythonic. Use NumPy's where() for large datasets requiring better performance. The range() approach works well when you specifically need explicit index control.
