Suraj Davey
Suraj Davey

Reputation: 19

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?

Upvotes: 0

Views: 147

Answers (5)

Daniel
Daniel

Reputation: 12026

Using a modification of itertools recipe unique_everseen for a solution that keeps track of new entries in a list.

from itertools import ifilterfalse
def unique_everseen(iterable, key=None, per_index=False):
    "List unique elements, preserving order. Remember all elements ever seen. 
    Use per_index=True to return indices instead of elements."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    # unique_everseen('ABBCcAD', str.lower, True) --> 0 1 3 6
    seen = set()
    seen_add = seen.add
    if key is None:
        for index, element in enumerate(ifilterfalse(seen.__contains__, iterable)):
            seen_add(element)
            yield element if not per_index else index
    else:
        for index, element in enumerate(iterable):
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element if not per_index else index

To try it out on your example:

list(unique_everseen(l1, per_index=True)) # returns [0, 1]

Upvotes: 0

Jacob Vlijm
Jacob Vlijm

Reputation: 3159

Assuming you need to show indexes of all occurrences where items change:

l = [1 ,2, 2, 3, 3, 1, 1]

changes = [i for i, n in list(enumerate(l))[1:] if l[i] != l[i-1]]

print(changes)
> [1, 3, 5]

This simply compares each item from the list with the previous one, lists where elements differ.

Upvotes: 0

Sayali Sonawane
Sayali Sonawane

Reputation: 12599

import numpy as np
UniqueList, indices = np.unique(l1, return_inverse=True)
print(UniqueList) #Unique elements in List l1

array([1, 2])

print(indices)  #indices of element in l1 mapped to UniqueList

array([0, 1, 1, 1])

Upvotes: 1

user3543300
user3543300

Reputation: 507

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.

Upvotes: 2

shiva
shiva

Reputation: 2699

Try this:

l1 = [1,2,2,2]

for pos, i in enumerate(l1):
    if l1.count(i)==1:      
        print pos

Upvotes: 0

Related Questions