Search code examples
pythonlistintegerminimum

Replace consecutive numbers in list with their min


I have a list of integers and some of them are consecutive. I would like to either replace the consecutive ones with their group's minimum or delete all of them except each group's minimum. Example:

my_list = [1,2,3,4,6,7,8,9,11]

result = [1,1,1,1,6,6,6,6,11]

or even deleting them like so:

result = [1,6,11]

Solution

  • For the second way,

    print([x for x in my_list if x-1 not in my_list])
    

    gives you the list of all numbers for which the previous is not in the original list