Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let’s discuss a shorthand by which we can perform this particular task.
Method : Using enumerate() + list comprehension This method can be performed using combination of functionalities. In this, we use enumerate function to access index-element together and list comprehension is used for iteration and logic creation.
Python3
test_list = [ 6 , 7 , 0 , 1 , 0 , 2 , 0 , 12 ]
print ("The original list is : " + str (test_list))
res = [idx for idx, val in enumerate (test_list) if val ! = 0 ]
print ("Indices of Non - Zero elements : " + str (res))
|
Output :
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0, 1, 3, 5, 7]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Using numpy:
Note: Install numpy module using command “pip install numpy”
Use the numpy library to find the indices of non-zero elements in the list. Time complexity of this approach would be O(n) and space complexity would be O(n)
Python3
import numpy as np
test_list = [ 6 , 7 , 0 , 1 , 0 , 2 , 0 , 12 ]
print ( "The original list is : " + str (test_list))
res = np.nonzero(test_list)[ 0 ]
print ( "Indices of Non-Zero elements : " + str (res))
|
Output :
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0 1 3 5 7]
This approach uses the numpy library’s nonzero() function to find the indices of non-zero elements in the list. Time complexity of this approach is O(n) and space complexity is O(n).
Method: Using a for loop
Python3
test_list = [ 6 , 7 , 0 , 1 , 0 , 2 , 0 , 12 ]
print ( "The original list is : " + str (test_list))
res = []
for i in range ( len (test_list)):
if test_list[i] ! = 0 :
res.append(i)
print ( "Indices of Non-Zero elements : " + str (res))
|
Output
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0, 1, 3, 5, 7]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using filter() function
The filter() function can be used to filter out the non-zero elements and return the indices of the remaining elements.
Step-by-step approach:
- Define a function that takes an element and its index as input and returns True if the element is non-zero, else False.
- Apply the filter() function on the enumerated test_list with the above-defined function.
- Convert the filtered output to a list and extract the indices using the map() function.
- Print the indices of non-zero elements
Python3
test_list = [ 6 , 7 , 0 , 1 , 0 , 2 , 0 , 12 ]
print ( "The original list is : " + str (test_list))
def filter_non_zero(elem):
return elem[ 1 ] ! = 0
filtered_output = filter (filter_non_zero, enumerate (test_list))
res = list ( map ( lambda x: x[ 0 ], filtered_output))
print ( "Indices of Non-Zero elements : " + str (res))
|
Output
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0, 1, 3, 5, 7]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as the space used is constant, and does not depend on the size of the input.
Method 5: Using the Itertools Module:
- Initialize the input list with some elements.
- Print the original input list to the console.
- Import the compress() function from the itertools module.
- Create a Boolean mask where True corresponds to non-zero elements in the input list.
- Use the compress() function to get an iterator object that returns only the elements from the input list that correspond to a True value in the Boolean mask.
- Convert the iterator object to a list and store it in a variable.
- Print the list of indices of non-zero elements to the console.
Python3
from itertools import compress
test_list = [ 6 , 7 , 0 , 1 , 0 , 2 , 0 , 12 ]
print ( "The original list is : " + str (test_list))
non_zero_indices = list (compress( range ( len (test_list)), test_list))
print ( "Indices of Non-Zero elements : " + str (non_zero_indices))
|
Output
The original list is : [6, 7, 0, 1, 0, 2, 0, 12]
Indices of Non-Zero elements : [0, 1, 3, 5, 7]
Time Complexity:
The compress() function works in linear time, O(n), where n is the length of the input list. Therefore, the overall time complexity of the algorithm is also O(n).
Auxiliary Space:
The algorithm uses an additional list to store the indices of non-zero elements. The size of this list is proportional to the number of non-zero elements in the input list, which is at most n. Therefore, the space complexity of the algorithm is O(n).
Method 6: Using a lambda function with the map() function
- Initialize a list test_list with values [6, 7, 0, 1, 0, 2, 0, 12].
- Use the enumerate() function to generate a sequence of (index, value) pairs for each element in the list. This generates a new sequence [(0, 6), (1, 7), (2, 0), (3, 1), (4, 0), (5, 2), (6, 0), (7, 12)].
- Use the filter() function to keep only the pairs where the value is non-zero. This filters the sequence to (0, 6), (1, 7), (3, 1), (5, 2), (7, 12).
- Use the map() function to extract the index value from each pair. A lambda function is used to take the first element of each pair. This returns a new sequence [0, 1, 3, 5, 7].
- Convert the resulting sequence of indices to a list and store it in the variable res.
- Print the list of indices using the print() function.
Python3
test_list = [ 6 , 7 , 0 , 1 , 0 , 2 , 0 , 12 ]
res = list ( map ( lambda x: x[ 0 ], filter ( lambda x: x[ 1 ] ! = 0 , enumerate (test_list))))
print ( "Indices of Non-Zero elements : " + str (res))
|
Output
Indices of Non-Zero elements : [0, 1, 3, 5, 7]
The time complexity of this method is O(n), where n is the length of the input list.
The auxiliary space complexity is O(n) as well, due to the use of the filter and map functions to generate a new list.
Last Updated :
09 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...