Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track value changes in a repetitive list in Python

I have a list with repeating values as shown below:

x = [1, 1, 1, 2, 2, 2, 1, 1, 1]

This list is generated from a pattern matching regular expression (not shown here). The list is guaranteed to have repeating values (many, many repeats - hundreds, if not thousands), and is never randomly arranged because that's what the regex is matching each time.

What I want is to track the list indices at which the entries change from the previous value. So for the above list x, I want to obtain a change-tracking list [3, 6] indicating that x[3] and x[6] are different from their previous entries in the list.

I managed to do this, but I was wondering if there was a cleaner way. Here's my code:

x = [1, 1, 1, 2, 2, 2, 1, 1, 1]

flag = []
for index, item in enumerate(x):
    if index != 0:
        if x[index] != x[index-1]:
            flag.append(index)

print flag

Output: [3, 6]

Question: Is there a cleaner way to do what I want, in fewer lines of code?

like image 807
prrao Avatar asked Jan 30 '15 18:01

prrao


People also ask

How do you check if an element is in a list multiple times Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().

How do you find the index of the same element in a list?

Find all indices of an item in list using list. index() returns the index of first occurrence of an item in list. So, to find other occurrences of item in list, we will call list. index() repeatedly with range arguments. We have created a function that uses list.

How do you check if two items are the same in a list Python?

Python sort() method and == operator to compare lists We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How do you repeat a value and time in a list in Python?

The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).


1 Answers

It can be done using a list comprehension, with a range function

>>> x = [1, 1, 1, 2, 2, 2, 3, 3, 3]
>>> [i for i in range(1,len(x)) if x[i]!=x[i-1] ]
[3, 6]
>>> x = [1, 1, 1, 2, 2, 2, 1, 1, 1]
>>> [i for i in range(1,len(x)) if x[i]!=x[i-1] ]
[3, 6]
like image 189
Bhargav Rao Avatar answered Oct 06 '22 01:10

Bhargav Rao