1

I have a one-dimensional array containing values and I'm trying to use a for loop to identify the index values associated with non-zero elements.

For the code below, non_zero_elements should contain the values 0, 1, and 4, but what I am getting is [1, 0, 0, 4, 0].

I tried referencing a similar thread (Finding Non-Zero Values/Indexes in Numpy) but couldn't identify the bug in my code.

a = [1,2,0,0,4,0]
non_zero_elements = []
i = 0
for i in a:
    if a[i] != 0:
        non_zero_elements.append(i)
        print('The value',a[i],'in index',i,'is a non-zero element.')
        i = i + 1
print('Non-zero elements: ',non_zero_elements)

3 Answers 3

5

An easy way to solve this is with a list comprehension over an enumerate, which gives you the index and the value, allowing you to filter on non-zero values:

a = [1,2,0,0,4,0]
non_zero_elements = [i for i, v in enumerate(a) if v != 0]
print(non_zero_elements)

Output:

[0, 1, 4]
Sign up to request clarification or add additional context in comments.

Comments

1

I think the way you were trying to do it, you meant to iterate over the indices and not the elements of list a.

a = [1,2,0,0,4,0]
non_zero_elements = []
i = 0
for i in range(0,len(a)):
    if a[i] != 0:
        non_zero_elements.append(i)
        print('The value',a[i],'in index',i,'is a non-zero element.')
        i = i + 1
print('Non-zero elements: ',non_zero_elements)

1 Comment

Thank you very much for the feedback, it was spot on.
1

for i in a: in this i is the value of items in a and not their index.

You can use for i, v in enumerate(a): to iterate over the list where i will be index and v will be the value at that index.

Alternately, you can use for i in range(len(a)): to iterate using the index and access a[i].

1 Comment

Thank you, Surender!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.