Last occurance of an item that is not a string in a list - Python

Viewed 49

I have list of lists of numbers e.g.

[[0,0,0,0,0], [1,1,0,0,0], [1,0,0,0,0], [0,0,0,0,0], [1,1,1,1,0]]

I would like to find the index of the last 1 in each list. The left most number is index 0.

The items in the list are not strings so I can't use ".rindex" function.

Thanks for any assistance.

2 Answers

You can use enumerate to get every index of 1 and extract the last element.

[[idx for idx,v in enumerate(i) if v==1][-1] if 1 in i else -1 for i in lst]
# [-1, 1, 0, -1, 3]

Or use str.rfind which wouldn't raise error when an element is not found it returns -1.

 [''.join(map(str,i)).rfind('1') for i in lst]
# [-1, 1, 0, -1, 3]

We can reverse the list (`list[::-1]) and then use the index function to find its location.

Finally, the indexes need to be adjusted using the list length (correcting for index numbers in python starting at 0.

data = [[0,0,0,0,0], [1,1,0,0,0], [1,0,0,0,0], [0,0,0,0,0], [1,1,1,1,0]]

# loop through all values (the lists) in data and select their last element.

last_list = [len(i) - i[::-1].index(1) - 1  if (1 in i) else None for i in data] 

Related