Suraj Davey Suraj Davey - 2 months ago 5
Python Question

How can I find the position in a list where an item differs from the previous item?

l1 = [1,2,2,2]


In the list above, I know that the element differs in l1[0]. Is there any way to find the position in python?

Answer

Try this:

l1.index(min(set(l1), key=l1.count))

EDIT:

The lambda expression min(set(l1), key=l1.count) tells us what is the element that occurs the fewest number of times in the list. Then we use l1.index to figure out the position of that element in the list.

Comments