James Lo
James Lo

Reputation: 37

how does append works with for loop in python

t=int(input())
#c=[i for i in range(t)]
for i in range(t):

    n=int(input())
    a = list(map(int,input().strip().split()))
    b = list()

    for i in range(n):
        if(a[i]==1):
            b.append(i)


    print(b)

when list a is (1 0 1) , list b is( 0,2 ) when list a is 1 0 0 1 , list b is 0 ,3 In fact , I suppose the output of list b is ( 1,1) instead of 0, 2 since its definition is to add the obj into list Please tell me if there's something I miss or get wrong , thanks

Upvotes: 1

Views: 41

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13393

You append i, which is the index, and not a[i] which is the value from a.

so b is essentially a list containing all indexes of elements in a that are equal 1

Upvotes: 2

Related Questions