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
# Python3 code to demonstrate
# Non-None elements indices
# 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
# Non-None elements indices
res = [i for i in range(len(test_list)) if test_list[i] != None]
# print result
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
# Python3 code to demonstrate
# Non-None elements indices
# 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
# Non-None elements indices
res = [i for i, val in enumerate(test_list) if val != None]
# print result
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
# Initializing list
test_list = [1, None, 4, None, None, 5]
# Zipping original list with range of its length
# Filtering out elements where original list value is None
filtered_list = filter(lambda x: x[0] != None, zip(test_list, range(len(test_list))))
# Extracting indices using lambda function
indices = list(map(lambda x: x[1], filtered_list))
# Printing result
print("The Non None indices list is : " + str(indices))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe 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 library
import numpy as np
# initializing list
test_list = [1, None, 4, None, None, 5]
# convert list to numpy array
arr = np.array(test_list)
# get indices where array elements are not None
non_none_indices = np.where(arr != None)[0]
# convert numpy array to list
res = non_none_indices.tolist()
# print result
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
# initializing list
test_list = [1, None, 4, None, None, 5]
# initializing empty list to store indices
non_none_indices = []
# iterating over the list
for i in range(len(test_list)):
if test_list[i] is not None:
non_none_indices.append(i)
# print result
print("The Non None indices list is : " + str(non_none_indices))
OutputThe 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 - Index Ranks of Elements
Given a list of elements, our task is to get the index ranks of each element. Index Rank of Number = (Sum of occurrence indices of number) / number Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9] Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6), (6, 0.3333
3 min read
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 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
Find index of element in array in python
We often need to find the position or index of an element in an array (or list). We can use an index() method or a simple for loop to accomplish this task. index() method is the simplest way to find the index of an element in an array. It returns the index of the first occurrence of the element we a
2 min read
Find Index of Element in Array - Python
In Python, arrays are used to store multiple values in a single variable, similar to lists but they offer a more compact and efficient way to store data when we need to handle homogeneous data types . While lists are flexible, arrays are ideal when we want better memory efficiency or need to perform
2 min read
Find element in Array - Python
Finding an item in an array in Python can be done using several different methods depending on the situation. Here are a few of the most common ways to find an item in a Python array.Using the in Operatorin operator is one of the most straightforward ways to check if an item exists in an array. It r
3 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
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