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 Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read