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
Python - Non-None elements indices
The problem at hand is to get the indices of non-None elements in a given input list. This is useful when working with datasets containing missing or empty values represented as None.
Understanding the Problem
Given a list containing some None values, we need to find the indices of all non-None elements. For example, given the list [1, None, 5, None, 8, 9], we should return [0, 2, 4, 5] as these are the positions of non-None values.
Method 1: Using a For Loop
The basic approach iterates through the list and checks each element ?
def get_non_none_indices(items):
indices = []
for i in range(len(items)):
if items[i] is not None:
indices.append(i)
return indices
# Test with sample data
the_list = [12, None, 54, None, 31, None, 42, None, 83]
non_none_indices = get_non_none_indices(the_list)
print("Original list:", the_list)
print("Non-None indices:", non_none_indices)
Original list: [12, None, 54, None, 31, None, 42, None, 83] Non-None indices: [0, 2, 4, 6, 8]
Method 2: Using List Comprehension
A more Pythonic approach using list comprehension with enumerate() ?
def get_non_none_indices_compact(items):
return [i for i, value in enumerate(items) if value is not None]
# Test with different data
data = ['apple', None, 'banana', None, 'cherry', 'date']
indices = get_non_none_indices_compact(data)
print("Original list:", data)
print("Non-None indices:", indices)
print("Non-None values:", [data[i] for i in indices])
Original list: ['apple', None, 'banana', None, 'cherry', 'date'] Non-None indices: [0, 2, 4, 5] Non-None values: ['apple', 'banana', 'cherry', 'date']
Method 3: Using NumPy
For numerical data, NumPy provides an efficient solution ?
import numpy as np
def get_non_none_indices_numpy(items):
arr = np.array(items, dtype=object)
return np.where(arr != None)[0].tolist()
# Test with numerical data
numbers = [10, None, 20, None, 30, 40, None]
indices = get_non_none_indices_numpy(numbers)
print("Original array:", numbers)
print("Non-None indices:", indices)
Original array: [10, None, 20, None, 30, 40, None] Non-None indices: [0, 2, 4, 5]
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| For Loop | O(n) | O(k) | Simple, readable code |
| List Comprehension | O(n) | O(k) | Pythonic, concise |
| NumPy | O(n) | O(k) | Large numerical datasets |
Where n is the list size and k is the number of non-None elements.
Conclusion
Use list comprehension with enumerate() for most cases as it's concise and Pythonic. For large numerical datasets, NumPy provides better performance. The basic for loop approach works well for beginners or when code clarity is prioritized.
