Sc4r
Sc4r

Reputation: 700

Returning the indices in a list

def test(lst):        
        new_lst = []
        for i in lst:
                if i is True:
                        new_lst.append(lst.index(i))
        return new_lst

What the above code is supposed to do:

Loops through each element in the list and if the element is True then append it's indice to a new list. However, it's not doing exactly what it's supposed to do and I can't figure out where I went wrong.

Expected:

test([1,2,3,True,True,False])
[3,4]

Got:

[0,0]

Upvotes: 0

Views: 85

Answers (3)

Paulo Bu
Paulo Bu

Reputation: 29794

You can use enumerate function and do it like this:

for index, elem in enumerate(lst):
    if elem is True:
        new_lst.append(index)

Your code returns [0,0]. This make sense because they are only two True values inside the list, but somehow in python list.index method when passed a True value will return the first trueish value, which in your case will be the first element in the lis 1 and thus you're getting [0,0] as a result.

Example of list.index behavior:

>>>l=[1,2,3,True,True,False]
>>>l.index(True)
1    # first trueish value

As pointed out by @MaxNoel list.index test equality, so like True == 1, index 0 is returned when searching for True's index.

Hope this helps!

Upvotes: 2

aIKid
aIKid

Reputation: 28292

list.index returns the index where the first match is found. Another mistake is because, list.index uses equality semantics - imagine the == symbol - and True == 1 returns True. For more details, see @max's answer

Use the built-in function enumerate instead:

for i, v in enumerate(lst):
    if v is True:
        new_lst.append(i)

Upvotes: 2

Max Noel
Max Noel

Reputation: 8910

That's not what your code returns. Your code returns [0, 0] because list.index uses equality semantics, not identity semantics, and True == 1 (try it).

As for a solution, use enumerate:

new_lst = [index for (index, element) in enumerate(lst) if element is True]

More info at http://docs.python.org/2/library/functions.html#enumerate

Upvotes: 7

Related Questions