Python – Non-None elements indices
Last Updated :
08 Apr, 2023
Many times while working in data science domain we need to get the list of all the indices which are Non 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 Not None.
Python3
test_list = [ 1 , None , 4 , None , None , 5 ]
print ("The original list : " + str (test_list))
res = [i for i in range ( len (test_list)) if test_list[i] ! = None ]
print ("The Non None indices list is : " + str (res))
|
Output :
The original list : [1, None, 4, None, None, 5]
The Non None indices list is : [0, 2, 5]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n).
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
test_list = [ 1 , None , 4 , None , None , 5 ]
print ("The original list : " + str (test_list))
res = [i for i, val in enumerate (test_list) if val ! = None ]
print ("The Non None indices list is : " + str (res))
|
Output :
The original list : [1, None, 4, None, None, 5]
The Non None indices list is : [0, 2, 5]
Time complexity: O(n), where n is the length of the input list test_list. This is because the code iterates through each element of the list once.
Auxiliary space: O(k), where k is the number of non-None elements in the input list.
Method #3: Using the built-in functions zip, range, filter, and lambda
Using the built-in functions zip, range, filter, and lambda, we can create a list of non-None indices by first zipping the original list with the range of its length, then filtering out the elements where the original list value is None, and finally extracting the indices using a lambda function.
Here’s an example of how this can be done:
Python3
test_list = [ 1 , None , 4 , None , None , 5 ]
filtered_list = filter ( lambda x: x[ 0 ] ! = None , zip (test_list, range ( len (test_list))))
indices = list ( map ( lambda x: x[ 1 ], filtered_list))
print ( "The Non None indices list is : " + str (indices))
|
Output
The Non None indices list is : [0, 2, 5]
Time complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using numpy
- Import the numpy library: import numpy as np
- Convert the list to a numpy array: arr = np.array(test_list). This creates a new numpy array from the original list.
- Get the indices where the array elements are not None: non_none_indices = np.where(arr != None)[0]. The where() function returns a tuple containing the indices where the specified condition is true. Since we only need the first element of the tuple (which contains the indices), we append [0] to the end of the function call.
- Convert the numpy array to a list: res = non_none_indices.tolist(). This creates a new list from the numpy array containing the non-None indices.
- Print the result: print(“The Non None indices list is : ” + str(res)). This displays the list of non-None indices in the output.
Python3
import numpy as np
test_list = [ 1 , None , 4 , None , None , 5 ]
arr = np.array(test_list)
non_none_indices = np.where(arr ! = None )[ 0 ]
res = non_none_indices.tolist()
print ( "The Non None indices list is : " + str (res))
|
Output:
The Non None indices list is : [0, 2, 5]
Time complexity: O(n)
Auxiliary Space: O(n)
Method 5 : Using a for loop
step by step approach :
- Create a list of integers and None values named test_list. The list contains 6 elements: [1, None, 4, None, None, 5].
- Create an empty list named non_none_indices. This list will store the indices of non-None elements from the test_list.
- Loop through the range of indices of test_list using a for loop. The range of indices is obtained using the range() function, which takes the length of test_list as its argument. This loop will iterate through all the elements of test_list.
- Check if the element at the current index in test_list is not None using an if statement. If it’s not None, then append the index of that element to the non_none_indices list.
- After iterating through all the elements of test_list, print the non_none_indices list using the print() function. The list will contain the indices of non-None elements from the test_list.
Python3
test_list = [ 1 , None , 4 , None , None , 5 ]
non_none_indices = []
for i in range ( len (test_list)):
if test_list[i] is not None :
non_none_indices.append(i)
print ( "The Non None indices list is : " + str (non_none_indices))
|
Output
The Non None indices list is : [0, 2, 5]
Time Complexity: O(n) where n is the length of the list.
Auxiliary Space: O(k) where k is the number of non-None elements in the list.
The time complexity is O(n) because we are iterating over the entire list once. The auxiliary space is O(k) because we are storing the indices of non-None elements in a separate list, which can have a maximum size of k.
Similar Reads
Python - Odd elements indices
Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Letâs discuss certain way to find indic
7 min read
Python - Minimum element indices
Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Letâs discuss a shorthand to ac
3 min read
Python - Optional padding in list elements
Optional padding in list elements involves adding extra elements, such as zeros or placeholders, to a list to ensure it reaches a desired length. This technique is useful when working with fixed-size data structures or when aligning data in lists. Using List ComprehensionThis method pads each elemen
2 min read
Python - Get Indices of Even Elements from list
Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let us discuss certain ways to find in
8 min read
Python - Elements with same index
Given a List, get all elements that are at their index value. Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9] Output : [1, 4, 6] Explanation : These elements are at same position as its number.Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9] Output : [] Explanation : No number at its index. Method #1:
5 min read
Python - Index Directory of Elements
Given a list of elements, the task is to write a python program to compute all the indices of all the elements. Examples: Input: test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8] Output: {8: [4, 8], 3: [2, 5], 6: [1, 6], 7: [0, 3, 7]} Explanation: 8 occurs at 4th and 8th index, 3 occurs at 2nd and 5th index a
3 min read
Python - Negative index of Element in List
We are given a list we need to find the negative index of that element. For example, we are having a list li = [10, 20, 30, 40, 50] and the given element is 30 we need to fin the negative index of it so that given output should be -3. Using index()index() method in Python searches for the first occu
3 min read
Handling " No Element Found in Index() " - Python
The task of handling the case where no element is found in the index() in Python involves safely managing situations where the desired element does not exist in a list. For example, with the list a = [6, 4, 8, 9, 10] and the element 11, we want to ensure the program doesn't raise an error if the ele
3 min read
Difference Between Nan and None in Python
Python is a dynamically typed language with multiple concepts which might get confusing as we get to the computational parts of the Python language. Understanding basic concepts becomes a part of getting to know about the thought process of working with such concepts. One of such ambiguities arrives
5 min read
Python - Flag None Element Rows in Matrix
Given a Matrix, return True for rows which contain a None Value, else return False. Input : test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8, None]] Output : [True, True, False, True] Explanation : 1, 2 and 4th index contain None occurrence. Input : test_list = [[2, 4, None, 3], [3
4 min read