1

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]
ComplicatedPhenomenon
  • 4,055
  • 2
  • 18
  • 45
theotheraussie
  • 495
  • 1
  • 4
  • 14
  • Well you cannot do better than O(n) which is iterating over the entire list, so what you have seems good enough – Devesh Kumar Singh Jul 18 '19 at 04:40
  • You did it with just one loop over the large list. I think this is the best you will get. You might find a function that does exactly that in some library and then your code will be one line but the function you will find is probably iterating over the large list as well. – yonBav Jul 18 '19 at 04:51
  • Possible duplicate of [Removing elements that have consecutive duplicates](https://stackoverflow.com/questions/5738901/removing-elements-that-have-consecutive-duplicates) – Georgy Jul 18 '19 at 12:46

1 Answers1

2

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]
Mark
  • 90,562
  • 7
  • 108
  • 148