The Wayback Machine - https://web.archive.org/web/20240821211804/https://www.geeksforgeeks.org/python-index-of-non-zero-elements-in-python-list/
Open In App

Python | Index of Non-Zero elements in Python list

Last Updated : 09 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Similar Reads

Python | Pandas Series.nonzero() to get Index of all non zero values in a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns i
2 min read
Minimum steps to make sum and the product of all elements of array non-zero
Given an array arr of N integers, the task is to find the minimum steps in which the sum and product of all elements of the array can be made non-zero. In one step any element of the array can be incremented by 1.Examples: Input: N = 4, arr[] = {0, 1, 2, 3} Output: 1 Explanation: As product of all elements of the array is zero Increment the array e
7 min read
How to check whether the elements of a given NumPy array is non-zero?
In NumPy with the help of any() function, we can check whether any of the elements of a given array in NumPy is non-zero. We will pass an array in the any() function if it returns true then any of the element of the array is non zero if it returns false then all the elements of the array are zero. Syntax: numpy.any() Parameter :An array. Return :It
1 min read
Test whether the elements of a given NumPy array is zero or not in Python
In numpy, we can check that whether none of the elements of given array is zero or not with the help of numpy.all() function. In this function pass an array as parameter. If any of one element of the passed array is zero then it returns False otherwise it returns True boolean value. Syntax: numpy.all( array ) Parameters: An array Return: Boolean va
2 min read
Get Index of Multiple List Elements in Python
In Python, retrieving the indices of specific elements in a list is a common task that programmers often encounter. There are several methods to achieve this, each with its own advantages and use cases. In this article, we will explore some different approaches to get the index of multiple list elements in Python. Get Index Of Multiple List Element
3 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Numpy: Index 3D array with index of last axis stored in 2D array
NumPy, or Numerical Python, is a powerful library for efficient numerical computation in Python. One of the key features of NumPy is its ability to perform advanced indexing, which allows to access and manipulate specific elements of an array based on complex conditions. In this article, we will explore how to index a 3D array using a 2D array of i
5 min read
Find indices of elements equal to zero in a NumPy array
Sometimes we need to find out the indices of all null elements in the array. Numpy provides many functions to compute indices of all null elements. Method 1: Finding indices of null elements using numpy.where() This function returns the indices of elements in an input array where the given condition is satisfied. Syntax : numpy.where(condition[, x,
3 min read
Python | Check if all values in numpy are zero
Given a numpy array, the task is to check whether the numpy array contains all zeroes or not. Let's discuss few ways to solve the above task. Method #1: Getting count of Zeros using numpy.count_nonzero() C/C++ Code # Python code to demonstrate # to count the number of elements # in numpy which are zero import numpy as np ini_array1 = np.array([1, 2
3 min read
Python | Replace negative value with zero in numpy array
Given numpy array, the task is to replace negative value with zero in numpy array. Let’s see a few examples of this problem. Method #1: Naive Method C/C++ Code # Python code to demonstrate # to replace negative value with 0 import numpy as np ini_array1 = np.array([1, 2, -3, 4, -5, -6]) # printing initial arrays print("initial array&qu
4 min read
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values
In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex input values in Python. This method substitutes a nan value with a number and replaces positive infinity
4 min read
Replace NaN with zero and fill negative infinity values in Python
In this article, we will cover how to replace NaN with zero and fill negative infinity values in Python using NumPy. Example Input: [ nan -inf 5.] Output: [0.00000e+00 9.99999e+05 5.00000e+00] Explanation: Replacing NaN with 0 and negative inf with any value. numpy.nan_to_num method The numpy.nan_to_num method is used to replace Nan values with zer
3 min read
Python NumPy - Return real parts if input is complex with all imaginary parts close to zero
In this article, we will discuss how to return real parts if the input is complex with all imaginary parts close to zero in Python. The numpy np.real_if_close() method is used to return the real parts if the input is a complex number with all imaginary parts close to zero. “Close to zero” is defined as tol * (machine epsilon of the type for a). syn
2 min read
ZeroDivisionError: float division by zero in Python
In this article, we will see what is ZeroDivisionError and also different ways to fix this error. What is ZeroDivisionError?A ZeroDivisionError in Python occurs when we try to divide a number by 0. We can't divide a number by 0 otherwise it will raise an error. Let us understand it with the help of an example. In this example, we are dividing a num
2 min read
Zerodivisionerror Integer by Zero in Python
Python, a versatile and powerful programming language, is widely used for various applications, from web development to data analysis. One common issue that developers often encounter is the ZeroDivisionError, which occurs when attempting to divide a number by zero. In this article, we will explore the causes of this error and provide practical sol
3 min read
Python | Returning index of a sorted list
Sort a list in python and then return the index of elements in sorted order. Examples: Input : [2, 3, 1, 4, 5] Output : [2, 0, 1, 3, 4] After sorting list becomes [1, 2, 3, 4, 5] and their index as [2, 0, 1, 3, 4] Input : [6, 4, 7, 8, 1] Output : [4, 1, 0, 2, 3] After sorting the list becomes [1, 4, 6, 7, 8] and their index as [4, 1, 0, 2, 3]. Meth
3 min read
Python - Append List every Nth index
Given 2 list, append list to the original list every nth index. Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = ['G', 'F', 'G'], N = 3 Output : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8] Explanation : List is added after every 3rd element.Input : test_list = [3, 7, 8, 2, 1, 5, 8, 9], app_list = ['G', 'F', 'G'], N = 4 O
5 min read
Get index in the list of objects by attribute in Python
In this article, we'll look at how to find the index of an item in a list using an attribute in Python. We'll use the enumerate function to do this. The enumerate() function produces a counter that counts how many times a loop has been iterated. We don't need to import additional libraries to utilize the enumerate() function because it's built-in t
2 min read
Python Indexerror: list assignment index out of range Solution
In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range. Python Indexerror: list assignment index out of range ExampleIf ‘fruits’ is a list, fruits=[‘Apple’,’ Banan
3 min read
Python List Index Out of Range - How to Fix IndexError
In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. List Index Out of Range Occur in Python when an item from a list is tried to be accessed that is outside the range of the list. Before we pr
3 min read
Python | Print list after removing element at given index
In this article, we will see how we can remove elements at a given index and print the list afterward. Example Input1: list = [10, 20, 30, 40, 50] index = 2 Output1: [10, 20, 40, 50] Input2: list = [10, 20, 40, 50] index = 0 Output2: [20, 40, 50] Print list after removing element at given indexBelow are the methods by which we can remove element at
3 min read
Python Program to Accessing index and value in list
There are various methods to access the elements of a list, but sometimes we may require to access an element along with the index on which it is found. Let's see all the different ways of accessing both index and value in a list. Accessing index and value in list Using Naive method This is the most generic method that can be possibly employed to p
5 min read
Python List index()
List index() method searches for a given element from the start of the list and returns the position of the first occurrence. Example: [GFGTABS] Python # list of animals Animals= ["cat", "dog", "tiger"] # searching positiion of dog print(Animals.index("dog")) [/GFGTABS]Output1 Definition of Python List index(
6 min read
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and t
2 min read
Replace all the NaN values with Zero's in a column of a Pandas dataframe
Replacing the NaN or the null values in a dataframe can be easily performed using a single line DataFrame.fillna() and DataFrame.replace() method. We will discuss these methods along with an example demonstrating how to use it. DataFrame.fillna(): This method is used to fill null or null values with a specific value. Syntax: DataFrame.fillna(self,
3 min read
Add zero columns to Pandas Dataframe
Prerequisites: Pandas The task here is to generate a Python program using its Pandas module that can add a column with all entries as zero to an existing dataframe. A Dataframe is a two-dimensional, size-mutable, potentially heterogeneous tabular data.It is used to represent data in tabular form like an Excel file format. Below is the syntax for cr
2 min read
Python3 Program for Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15}; Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} a
3 min read
How to Pad the Input Tensor Boundaries with Zero in PyTorch
In this article, we will discuss how to pad the input tensor boundaries with zero in Python using PyTorch. torch.nn.ZeroPad2D() method This method has accepted the size of padding as input and returns a new tensor with boundaries. The boundaries may be the same or different from all sides (left, right, top, bottom). we can increase the height and w
2 min read
Python3 Program to Find all triplets with zero sum
Given an array of distinct elements. The task is to find triplets in the array whose sum is zero. Examples :  Input : arr[] = {0, -1, 2, -3, 1} Output : (0 -1 1), (2 -3 1) Explanation : The triplets with zero sum are 0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5} Output : 1 -2 1 Explanation : The triplets with zero sum is 1 + -2
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg