Search code examples
pythonpython-3.xloopsfor-loopnested-loops

break a for loop without resetting its index in Python


no_elements = int(input())
seq = list(map(int, input().split()))
new_seq = []
diff = []
diff_opp = []

new_seq.append(seq[0])

for element in range(no_elements - 1):
    diff.append(seq[element + 1] - seq[element])

for element in range(no_elements - 1):
    diff[element] = -diff[element]


for diff_element in range(0, len(diff)):
    print(diff_element)
    for i in range(4):
            print(i)
            new_seq.append(diff[diff_element] + new_seq[i])
            break


print(new_seq)

Actually, I want that my nested (2nd) loop should do its work only 1 time and break every time it does so, plus I also want that value of i is not reset every time i say break as i am working with a list (new_seq) and in that I don't want to the same work with same number, instead i want that value of i doesn't change and i can do the logic with the whole list.

BTW I want to calculate the difference between each 2 elements in the list and then find its inverse(inverse of sign) and find a new sequence starting with the first element of the original sequence.

enter image description here

This is the actual question.☝


Solution

  • I have edited my first answer based on your new information

    seq = [-321, 524, 12, 0, 924, -658, -2]
    diff = list()
    
    for ii, element in enumerate(seq[1:]):
        diff.append(-(element - seq[ii]))
    
    new_value = seq[0]
    new_seq = [new_value]
    for value in diff:
        new_value += value
        new_seq.append(new_value)
    
    print(seq)
    print(diff)
    print(new_seq)
    

    This will give the output

    [-321, 524, 12, 0, 924, -658, -2]
    [-845, 512, 12, -924, 1582, -656]
    [-321, -1166, -654, -642, -1566, 16, -640]
    

    The output corresponds with your example

    For completeness, also the numpy version:

    import numpy as np
    seq = np.array([-321, 524, 12, 0, 924, -658, -2])
    diff = -np.diff(seq)
    new_seq = np.cumsum(np.hstack([seq[0], diff]))