Search code examples
pythonfor-loopif-statementwhile-loopappend

python list iteration over a sequence of numbers with "breaking points"


I have a list of numbers :

list = [1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,7,8]

I would like through iteration to take all the numbers of every breaking point. Let's say from 3 to 1 i want to keep 3, from 4 to 1 i want to keep 4 and keep also the last number of the list and append it to a new list. I would like to have an output:

new_list = [3,4,5,8]


Solution

  • list = [1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,7,8]
    new_list = []
    
    last_index = len(list)-1
    
    #Iterate till last but one-element
    for i in range(last_index):
        #If the number is greater than the next number, append it
        if list[i] > list[i+1]:
            new_list.append(list[i])
    
    #The last element will come in the list even if it is smaller than its previous number
    new_list.append(list[last_index])
    
    print(new_list)