theotheraussie
theotheraussie

Reputation: 495

Python Subsetting a list with changing value in list

I would like to get a list of values that change from the previous value from a larger list. I have tried creating the list by looping over the larger list, but I'm hoping there is a better way to do this, because i would like to save time searching over a large list.

sublist= [largerList[0]]
previous = largerList[0]
for item in largerList:
    if item != previous:
        sublist.append(item)
        previous = item

if

LargerList = [10,10,10,10,10,0,10,10,10,10,15,15,15,15,15,10,10,0,10,10,12,12,12,0]

I want

sublist = [10,0,10,15,10,0,10,12,0]

Upvotes: 1

Views: 38

Answers (1)

Mark
Mark

Reputation: 92440

You can use itertools.groupby to do this efficiently with less code. It still needs to look at every item. By default groupby will group by value, and the key will be the value of the groups. So just collect the keys:

from itertools import groupby

LargerList = [10,10,10,10,10,0,10,10,10,10,15,15,15,15,15,10,10,0,10,10,12,12,12,0]
sublists = [k for k, _ in groupby(LargerList)]

Sublists:

[10, 0, 10, 15, 10, 0, 10, 12, 0]

Upvotes: 2

Related Questions