Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Find indices with None values in given list

Python | Find indices with None values in given list

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


Output

The 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.


Output

The 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:

  1. Initialize an empty list res to store the indices of None elements.
  2. 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.
  3. 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))


Output

The 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:

  1. Initialize a list called res to store the indices of None values in the input list.
  2. 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.
  3. If the value at the current index is None, add the index to the res list. Otherwise, return the res list unchanged.
  4. 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.


Output

The 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).

RELATED ARTICLES

Most Popular

Recent Comments