Ad

How To Break Loop If Variable Changes

- 1 answer

I am running a for loop, in which the iterator loops through list of time based values.

for example this is what my list looks like

lst = ['00:00:01', '00:00:05', '00:00:07', '00:01:10', ... , '00:20:23']

I want to check if the minute part of the time data changes. If it changes then break the loop.

this is my code so far

time_lst = []

for time in lst:
    minute = time[3:5]

    if minute changes:
        time_lst.append(time)
        break

print(time_lst)

in the above program, how do I program the if condition?

I looked online but I could not find a good solution to this problem.

Ad

Answer

EDIT

With edited question so that it keeps changes of time between minutes

time_lst = []
lastMinute = lst[0][3:5] #so that it won't break on first item
for time in lst:
    minute = time[3:5]

    if minute != lastMinute: # `<>` still usable in python2, `!=` is better for compatibility between python2 and python3
        time_lst.append(time)
    lastMinute = minute

print(time_lst)
Ad
source: stackoverflow.com
Ad