Monday, November 18, 2024
Google search engine
HomeLanguagesPython | Index of Non-Zero elements in Python list

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




# Python3 code to demonstrate working of
# Index of Non-Zero elements in Python list
# using list comprehension + enumerate()
 
# initialize list
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Index of Non-Zero elements in Python list
# using list comprehension + enumerate()
res = [idx for idx, val in enumerate(test_list) if val != 0]
 
# printing result
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
 
# initialize list
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Find the indices of non-zero elements using numpy
res = np.nonzero(test_list)[0]
 
# printing result
print("Indices of Non-Zero elements : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


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




# Initializing list
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Index of Non-Zero elements in Python list
# using for loop
res = []
for i in range(len(test_list)):
    if test_list[i] != 0:
        res.append(i)
 
# Printing result
print("Indices of Non-Zero elements : " + str(res))
#This code is contributed by Vinay Pinjala.


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




# Python3 code to demonstrate working of
# Index of Non-Zero elements in Python list
# using filter() function
 
# initialize list
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
 
# printing original list
print("The original list is : " + str(test_list))
 
# function to filter non-zero elements
def filter_non_zero(elem):
    return elem[1] != 0
 
# Index of Non-Zero elements in Python list
# using filter() function
filtered_output = filter(filter_non_zero, enumerate(test_list))
res = list(map(lambda x: x[0], filtered_output))
 
# printing result
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:

  1. Initialize the input list with some elements.
  2. Print the original input list to the console.
  3. Import the compress() function from the itertools module.
  4. Create a Boolean mask where True corresponds to non-zero elements in the input list.
  5. 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.
  6. Convert the iterator object to a list and store it in a variable.
  7. Print the list of indices of non-zero elements to the console.

Python3




from itertools import compress
 
# initialize list
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using itertools.compress() to get the indices of non-zero elements
non_zero_indices = list(compress(range(len(test_list)), test_list))
 
# printing result
print("Indices of Non-Zero elements : " + str(non_zero_indices))
#This code is contributed by Jyothi pinjala.


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

  1. Initialize a list test_list with values [6, 7, 0, 1, 0, 2, 0, 12].
  2. 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)].
  3. 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).
  4. 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].
  5. Convert the resulting sequence of indices to a list and store it in the variable res.
  6. 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.

RELATED ARTICLES

Most Popular

Recent Comments