Muhammad Ardi Putra
Muhammad Ardi Putra

Reputation: 43

Why Python append function does not work in this case?

I am trying to find the indices of the misclassified samples using the following code. But I found that the append function does not actually append the index. Can anyone explain why is this happening?

for i in range(len(predictions)):
    misclassified_indices = []
    if y_test[i] != predictions[i]:
        print(i)
        misclassified_indices.append(i)
        
print(misclassified_indices)
19
357
1553     # All misclassified samples are printed correctly ...
[]       # ... but it does not append to this list

Upvotes: 1

Views: 58

Answers (3)

Timur Shtatland
Timur Shtatland

Reputation: 12347

You should initially assign your list outside the loop:

misclassified_indices = []
for i in range(len(predictions)):

In your original code, misclassified_indices is reassigned back to an empty list on every loop iteration, which causes it to be empty at the end.

You can also shorten your code using list comprehension:

misclassified_indices = [i for i in range(len(predictions)) if y_test[i] != predictions[i]]

Upvotes: 2

ScienceSnake
ScienceSnake

Reputation: 617

Because you reset the misclassified_indices to [] inside the loop. Just move your second line to outside of the loop.

Upvotes: 4

Bennimi
Bennimi

Reputation: 512

try to put the list outside of the loop:

misclassified_indices = [] # <-- goes here
for i in range(len(predictions)):
    
    if y_test[i] != predictions[i]:
        print(i)
        misclassified_indices.append(i)
        
print(misclassified_indices)

Upvotes: 3

Related Questions