Python | Find indices with None values in given list
Last Updated :
19 Apr, 2023
Many times while working in data science domain we need to get the list of all the indices which are None, so that they can be easily be prepossessed. This is quite a popular problem and solution to it comes quite handy. Let's discuss certain ways in which this can be done.
Method #1 : Using list comprehension + range() In this method we just check for each index using the range function and store the index if we find that index is None.
Python3
# Python3 code to demonstrate
# finding None indices in list
# using list comprehension + enumerate
# initializing list
test_list = [1, None, 4, None, None, 5]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + enumerate
# finding None indices in list
res = [i for i in range(len(test_list)) if test_list[i] == None]
# print result
print("The None indices list is : " + str(res))
Output : The original list : [1, None, 4, None, None, 5]
The None indices list is : [1, 3, 4]
Method #2 : Using list comprehension + enumerate() The enumerate function can be used to iterate together the key and value pair and list comprehension can be used to bind all this logic in one line.
Python3
# Python3 code to demonstrate
# finding None indices in list
# using list comprehension + enumerate
# initializing list
test_list = [1, None, 4, None, None, 5]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + enumerate
# finding None indices in list
res = [i for i, val in enumerate(test_list) if val == None]
# print result
print("The None indices list is : " + str(res))
Output : The original list : [1, None, 4, None, None, 5]
The None indices list is : [1, 3, 4]
Method #3 : Using filter() and lambda
Alternatively, you can use the filter function and a lambda function to achieve the same result:
Python3
test_list = [1, None, 4, None, None, 5]
# Use the filter function and a lambda function to get a generator
# that yields tuples of the form (index, element) for which the element
# is None.
indices = filter(lambda i_x: i_x[1] is None, enumerate(test_list))
# Use a list comprehension to extract the indices from the tuples
# returned by the generator.
res = [i for i, x in indices]
print("The None indices list is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe None indices list is : [1, 3, 4]
This code first uses the enumerate function to generate tuples of the form (index, element) for each element in test_list. It then uses the filter function and a lambda function to filter out the tuples for which the element is not None. The lambda function receives a tuple i_x and returns True if the second element of the tuple (i.e. i_x[1]) is None, and False otherwise. The filter function returns a generator that yields the tuples for which the lambda function returned True.
Finally, the code uses a list comprehension to extract the indices from the tuples returned by the generator and stores them in the result list.
In terms of time complexity, this code has a complexity of O(n) since it needs to iterate through the list once to generate the tuples and filter them. In terms of space complexity, it has a complexity of O(n).
Method#4: Using Recursive method.
The method takes in the list and an optional index parameter that defaults to 0. It recursively traverses the list and checks whether the current element is None. If it is, it adds the index to the result list and continues the recursion on the next index. Otherwise, it just continues the recursion on the next index. Once it reaches the end of the list, it returns the accumulated result list.
Python3
test_list = [1, None, 4, None, None, 5]
def get_none_indices(lst, i=0):
if i >= len(lst):
return []
elif lst[i] is None:
return [i] + get_none_indices(lst, i+1)
else:
return get_none_indices(lst, i+1)
res = get_none_indices(test_list)
print("The None indices list is : " + str(res))
#This code is contributed by Tvsk.
OutputThe None indices list is : [1, 3, 4]
Time complexity: O(n), where n is the length of the list. This is because the method traverses the entire list once.
Auxiliary Space: O(n), where n is the number of None elements in the list. This is because the method stores the index of each None element in the result list.
Method #5: Using a for loop
Step-by-step approach:
- Initialize an empty list res to store the indices of None elements.
- Use a for loop to iterate over the input list test_list:
a. Check if the current element is None using the is operator.
b. If it is None, append the index of the current element to the res list using the append() method. - After the loop completes, print the result.
Python3
test_list = [1, None, 4, None, None, 5]
# initialize an empty list to store the indices of None elements
res = []
# iterate over the list and append the index of each None element to the res list
for i in range(len(test_list)):
if test_list[i] is None:
res.append(i)
# print the result
print("The None indices list is : " + str(res))
OutputThe None indices list is : [1, 3, 4]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of None elements in the input list.
Method #5: Using numpy.where() function
Step-by-step approach:
- Import the numpy library
- Initialize the list to be tested, test_list
- Use numpy.where() function to get the indices of None values in test_list
- Store the indices obtained in a new variable, res
- Print the original list and the indices obtained using numpy.where() function
Python3
# import numpy library
import numpy as np
# initializing list
test_list = [1, None, 4, None, None, 5]
# using numpy.where() function
# finding None indices in list
res = np.where(np.array(test_list) == None)[0]
# print original list
print("The original list : " + str(test_list))
# print result
print("The None indices list is : " + str(list(res)))
OUTPUT:
The original list : [1, None, 4, None, None, 5]
The None indices list is : [1, 3, 4]
Time complexity: O(n)
Auxiliary space: O(n)
Method #6: Using reduce():
Algorithm:
- Initialize a list called res to store the indices of None values in the input list.
- Use the reduce() function to iterate over the indices of the input list and accumulate a list of indices of None values in the res list.
- If the value at the current index is None, add the index to the res list. Otherwise, return the res list unchanged.
- Return the res list containing the indices of all None values in the input list.
Python3
from functools import reduce
test_list = [1, None, 4, None, None, 5]
# print original list
print("The original list : " + str(test_list))
def get_none_indices(lst):
return reduce(lambda a, b: a + ([b] if lst[b] is None else []), range(len(lst)), [])
res = get_none_indices(test_list)
print("The None indices list is : " + str(res))
#This code is contributed by Rayudu.
OutputThe original list : [1, None, 4, None, None, 5]
The None indices list is : [1, 3, 4]
Time Complexity:
The reduce() function iterates over the indices of the input list once, so the time complexity of the get_none_indices() function is O(n), where n is the length of the input list.
Space Complexity:
The get_none_indices() function uses a list called res to store the indices of None values in the input list. The length of this list can be at most n, where n is the length of the input list. Therefore, the space complexity of the function is O(n).
Similar Reads
Python - Ways to find indices of value in list
In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Python | Get indices of True values in a binary list
Boolean lists are often used by developers to check for True values during hashing. The boolean list is also used in certain dynamic programming paradigms in dynamic programming. Let's discuss certain ways to get indices of true values in a list in Python. Method #1 : Using enumerate() and list comp
9 min read
Python | Initialize dictionary with None values
Sometimes, while working with dictionaries, we might have a utility in which we need to initialize a dictionary with None values so that they can be altered later. This kind of application can occur in cases of memoization in general or competitive programming. Let's discuss certain ways in which th
4 min read
How to Find Index of Item in Python List
To find the index of given list item in Python, we have multiple methods depending on specific use case. Whether weâre checking for membership, updating an item or extracting information, knowing how to get an index is fundamental. Using index() method is the simplest method to find index of list it
2 min read
Python - Create a Dictionary using List with None Values
The task of creating a dictionary from a list of keys in Python involves transforming a list of elements into a dictionary where each element becomes a key. Each key is typically assigned a default value, such as None, which can be updated later. For example, if we have a list like ["A", "B", "C"],
3 min read
Accessing index and value in Python list
We are given a list, and our task is to access both the index and value of each element in the list using Python. For example, using enumerate(list) in a loop like for index, value in enumerate(list) allows us to access both the index and the value together.Using enumerate() enumerate() is preferred
2 min read
Python | Find mismatch item on same index in two list
Given two list of integers, the task is to find the index at which the element of two list doesn't match. Input: Input1 = [1, 2, 3, 4] Input2 = [1, 5, 3, 6] Output: [1, 3] Explanation: At index=1 we have 2 and 5 and at index=3 we have 4 and 6 which mismatches. Below are some ways to achieve this tas
4 min read
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Python - Remove elements at Indices in List
Given List, remove all the elements present in the indices list in Python. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5]Â Output : [5, 6, 7, 2, 10]Â Explanation : 3, 6, and 1 has been removed. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2]Â Output : [5, 6, 7, 8,
7 min read
Python - Values Frequency Index List
Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of
4 min read